Open In App

JavaScript Sort() Method

The Javascript array.sort() is an inbuilt method in JavaScript that is used to sort the array. An array can be of any type i.e. string, numbers, characters, etc. Here array is the set of values that are going to be sorted. 

Syntax:



array.sort()

Parameters: It does not accept any parameters. 

Return values: It does not return anything. 



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

Example 1: To sort an array of strings: 




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.




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 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.


Article Tags :