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
function func() {
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Jul, 2023
Like Article
Save Article