English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript array sort() method

 JavaScript Array Object

sort()Methods sort the elements of the array (based on the first character) and return the array.

By default,sort()Methods are sorted in ascending order/Sort values in dictionary order.

This applies to strings ('December' comes before 'February').

But if the numbers are sorted as strings, then “35”is greater than “150”, because “3”is greater than “1

However, you can change the sorting algorithm by providing a 'compare' function.

Note: The sort() method changes the original array.

Syntax:

array.sort(compareFunction)
var months = [#39;March#39;, #39;Jan#39;, #39;Feb#39;, #39;Dec#39;];
months.sort();
Test and see‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the sort() method:

Method
sort()11IsIs5.5

Parameter value

ParameterDescription
compareFunction(Optional) Specify a function to define the sort order. If omitted, the array is sorted in dictionary order.

Technical details

Return value:Sorted array
JavaScript Version:ECMAScript 1

More Examples

Sort the numbers in the array in ascending order:

var nums = [5, 1, 2, 7, 3, 6, 4];
nums.sort();
Test and see‹/›

sort()By default, the number array is not sorted by size. Instead, it only checks the first character in the number:

var nums = [5, 1, 2, 17, 13, 6, 34];
nums.sort();
Test and see‹/›

To sort numbers correctly, you can create a comparison function as a parameter:

var nums = [5, 1, 2, 17, 13, 6, 34];
nums.sort(function(a, b) {return a - b});
Test and see‹/›

Sort the numbers in the array in descending order:

var nums = [5, 1, 2, 17, 13, 6, 34];
nums.sort(function(a, b) {return b - a});
Test and see‹/›

Get the minimum and maximum values in the array:

function myFunc() {
var nums = [5, 1, 2, 7, 3, 6, 4];
nums.sort(); // Array Sorting
var low = nums[0];   // The value of the first index is the smallest
var high = nums[nums.length-1];  // The last index has the largest value
}
Test and see‹/›

 JavaScript Array Object