The Array.sort()
method is a built-in JavaScript function used to sort the elements of an array in place. It organizes the elements either in ascending or descending order based on a specified compare function.
By default, the sort()
method converts elements to strings and sorts them lexicographically, which can lead to unexpected results when sorting numbers.
Syntax
arr.sort(compareFunction);
Parameters
Parameter | Description |
---|---|
compareFunction | (Optional) A function that defines the sort order. If omitted, elements are converted to strings and sorted lexicographically. |
Return Value
The sort()
method returns the sorted array. The original array is modified.
Example 1: Default Lexicographic Sorting
let arr = ['banana', 'apple', 'mango', 'cherry']; arr.sort(); console.log(arr); // Output: ['apple', 'banana', 'cherry', 'mango']
By default, sort()
method arrange elements in lexicographic (dictionary) order.
Example 2: Sorting Numbers Without a Compare Function
let arr = [10, 101, 1, 25, 3]; arr.sort(); console.log(arr); // Output: [1, 10, 101, 25, 3]
Without a compare function, numbers are treated as strings and sorted lexicographically, resulting in incorrect numerical order.
Example 3: Sorting Numbers with a Compare Function
let arr = [10, 101, 1, 25, 3]; arr.sort((a, b) => a - b); console.log(arr); // Output: [ 1, 3, 10, 25, 101 ]
Here, the compare function a - b
ensures correct numerical sorting in ascending order.
Example 4: Descending Order Sorting
let arr = [10, 101, 1, 25, 3]; arr.sort((a, b) => b - a); console.log(arr); // Output: [101, 25, 10, 3, 1]
By reversing the order in the compare function (b - a
), the array is sorted in descending order.
Example 5: Sorting an Array of Strings with Case Sensitivity
let arr = ['banana', 'apple', 'Apple', 'cherry']; arr.sort(); console.log(arr); // Output: [ 'Apple', 'apple', 'banana', 'cherry' ]
By default, sort()
is case-sensitive and places uppercase letters before lowercase ones due to Unicode values.
Example 6: Sorting an Array of Objects
let users = [ { name: 'John', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Bob', age: 20 } ]; users.sort((a, b) => a.age - b.age); console.log(users); /* Output: [ { name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Alice', age: 30 } ] */
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |