JavaScript Sort() Method

The sort() method in JavaScript sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings in ascending order. A custom comparison function can be provided to determine the sort order for different data types.

Examples:

Input:  let arr = ["Manish", "Rishabh", "Nitika", "Harshita"];
Output: Harshita, Manish, Nitika, Rishabh
Input: let arr = [1, 4, 3, 2];
Output: 1, 2, 3, 4

Syntax:

array.sort()

Parameters: It does not accept any parameters. 

Return values: It does not return anything. 

Example : To sort an array of strings: 

javascript
let names = ["Manish", "Rishabh", "Nitika", "Harshita"];
names.sort();
console.log(names);

Output
[ 'Harshita', 'Manish', 'Nitika', 'Rishabh' ]

Example 2: In this example we will use sorting to sort the array of integers.

javascript
let numbers = [30, 1, 6, 21, 100];
numbers.sort();
console.log(numbers);

Output
[ 1, 100, 21, 30, 6 ]

Example 3: In this example, the sort() method the elements of the array are sorted according to the function applied to each element.

Javascript
// JavaScript to illustrate sort() function
function func() {

    // Original array
    let arr = [2, 5, 8, 1, 4];
    console.log(arr.sort(function (a, b) {
        return a + 2 * b;
    }));
    console.log(arr);
}
func();

Output
[ 2, 5, 8, 1, 4 ]
[ 2, 5, 8, 1, 4 ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Contact Us