JavaScript Array sort() method
The sort()
method in JavaScript is used to sort the elements of an array in place and return the sorted array. The sorting can be done either in ascending or descending order, depending on the provided compareFunction
. If no compareFunction
is provided, the array elements are sorted as strings in ascending order.
Syntax:
compareFunction
(optional): A function that defines the sort order. It takes two arguments (let's call thema
andb
) and returns:- A negative value if
a
should be sorted beforeb
. - A positive value if
a
should be sorted afterb
. - Zero if
a
andb
are considered equal in the sort order.
- A negative value if
Return Value:
- The sorted array. The original array is modified.
Key Points:
- In-place sorting: The original array is modified; it does not create a new array.
- Default behavior: Without a
compareFunction
, elements are converted to strings and sorted according to their Unicode code point order. This can lead to unexpected results when sorting numbers. - Stability: The
sort()
method is not guaranteed to be stable in JavaScript (meaning the order of equal elements is not guaranteed to remain the same).
Example 1: Basic usage (Sorting strings)
Example 2: Sorting numbers with a compare function
Example 3: Sorting numbers in descending order
Example 4: Sorting objects by a property
Example 5: Sorting strings with a custom order
Example 6: Default behavior with numbers
Summary:
- The
sort()
method is a powerful tool for sorting arrays in JavaScript. - By providing a
compareFunction
, you can control the sorting order, whether it's numerical or based on specific properties of objects. - Be cautious when using the default behavior for numerical arrays, as it may yield unexpected results by treating numbers as strings. Always use a
compareFunction
for sorting numbers to ensure correct ordering.