Open In App

JavaScript Sort() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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: 

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:

  • Google Chrome 69 and above
  • Edge 79 and above
  • Firefox 62 and above
  • Opera 56 and above
  • Safari 12 and above

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.



Last Updated : 17 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads