JavaScript | Array sort()
arr.sort() function is used to sort the array in place in a given order according to the compare() function. If the function is omitted then the array is sorted in ascending order.
Syntax: arr.sort([compareFunction])
Arguments
The only argument to this function is a compare function that is used to sort the elements according to different attributes and in the different order.
- compareFunction(a,b) < 0
- compareFunction(a,b) > 0
- compareFunction(a,b) = 0
Then a comes before b in the answer.
Then b comes before a in the answer.
Then the order of a and b remains unchanged.
Return value
This function returns the reference of the sorted original array.
Examples for the above function are provided below:
Example 1:
var arr = [2, 5, 8, 1, 4] print(arr.sort()); print(arr);
Output:
1,2,4,5,8 1,2,4,5,8
In this example the function sort() arranges the elements of the array in ascending order.
Example 2:
var arr = [2, 5, 8, 1, 4]
print(arr.sort(function(a, b) {
return a + 2 * b;
}));
print(arr);
Output:
2,5,8,1,4 2,5,8,1,4
In this example the function sort() the elements of the array are sorted according the function applied on each element.
Codes for the above function are provided below:
Program 1:
<script> // JavaScript to illustrate sort() function function func() { //Original string var arr = [2, 5, 8, 1, 4] //Sorting the array document.write(arr.sort()); document.write("<br>"); document.write(arr); } func(); </script> |
Output:
1,2,4,5,8 1,2,4,5,8
Program 2:
<script> // JavaScript to illustrate sort() function function func() { // Original array var arr = [2, 5, 8, 1, 4]; document.write(arr.sort(function(a, b) { return a + 2 * b; })); document.write("<br>"); document.write(arr); } func(); </script> |
Output:
4,1,8,5,2 4,1,8,5,2
Recommended Posts:
- Sort an Object Array by Date in JavaScript
- Sort array of objects by string property value in JavaScript
- JavaScript | Sort() method
- How to sort strings in JavaScript?
- How to sort rows in a table using JavaScript?
- JavaScript | typedArray.sort() with Examples
- Merge Sort for Linked Lists in JavaScript
- JavaScript | Array pop()
- RMS Value Of Array in JavaScript
- How to use loop through an array in JavaScript?
- JavaScript | Array.from() method
- How to add an object to an array in JavaScript ?
- Array of functions in JavaScript
- How to convert Set to Array in JavaScript?
- How to empty an array in JavaScript?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



