The sort()
method in JavaScript is used to sort the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values.
Syntax
array.sort(compareFunction);
Parameters
Parameters | Descriptions |
---|---|
compareFunction (Optional) | Specifies a function that defines the sort order. If omitted, the array is sorted according to each character’s Unicode point value, according to the string conversion of each element.
|
Return Value
Return Type | Description |
---|---|
Array | The sorted array. |
Example 1: Sorting Numbers
This example demonstrates how to use the sort()
method to sort an array of numbers.
let Arr = [4, 2, 5, 1, 3]; Arr.sort((a, b) => a - b); console.log('Sorted Array:', Arr);
Output:
Sorted Array: [ 1, 2, 3, 4, 5 ]
Example 2: Sorting Strings
You can also use the sort()
method to sort an array of strings.
let Arr = ['Banana', 'Orange', 'Apple', 'Mango']; Arr.sort(); console.log('Sorted Array:', Arr);
Output:
Sorted Array: [ 'Apple', 'Banana', 'Mango', 'Orange' ]
Note
By default, the sort()
method sorts elements as strings. This may cause unexpected behavior when sorting numbers. To avoid this, the compareFunction
can be used to specify the sorting order.
Browsers Compatibility
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |