JavaScript’s sort()method: From basics to custom sorting

Table of Contents
- Introduction to JavaScript's sort() method
- Sorting Arrays in Ascending and Descending Order
- Custom Sorting with a Compare Function
- Sorting an Array of Objects
1. Introduction to JavaScript's sort() method <a name="introduction"></a>
- When
sort()
is used without a compare function, elements are first coerced to strings and sorted based on their UTF-16 code units. - Characters in strings are encoded as 16-bit code units in UTF-16.
- Non-string values are also coerced to strings before sorting.
2. Sorting Arrays in Ascending and Descending Order <a name="sorting-arrays"></a>
- By default,
sort()
sorts elements in ascending order based on their UTF-16 code units. - To sort in descending order, a custom compare function can be used.
array.sort((a, b) => b - a);
3. Custom Sorting with a Compare Function <a name="custom-sorting"></a>
- The compare function should return a negative number if the first argument should come before the second.
- It should return a positive number if the second argument should come before the first, and zero if they are equal.
- Example compare function for sorting numbers in ascending order:
array.sort((a, b) => a - b);
4. Sorting an Array of Objects <a name="sorting-objects"></a>
- Objects can be sorted based on a specific property using the compare function.
- Example sorting objects alphabetically by a property:
array.sort((a, b) => a.property.localeCompare(b.property));
Please note that sort()
mutates the original array. To avoid mutation, create a new array before sorting or use slice()
method for sorting. The compare function should be pure for consistent behavior.