JavaScript’s sort() method: From basics to custom sorting
Blog post from LogRocket
JavaScript offers two primary methods for sorting arrays: `Array.prototype.sort` and `Array.prototype.toSorted`. Both methods allow customizable sorting through a compare function, which determines the order of elements based on their values. By default, without a compare function, both methods convert elements to strings and sort them according to their UTF-16 code units, which can lead to unexpected results, such as "123" being sorted before "20" due to character code comparisons. The `sort` method mutates the original array, while `toSorted` returns a new array, preserving the original. For language-sensitive string sorting, JavaScript provides the `Intl.Collator` object and the `String.prototype.localeCompare` method, which accommodate different languages' sorting rules. These methods are not limited to arrays and can be applied to array-like objects with a length property. The choice between `sort` and `toSorted` depends on whether the original array should be altered or not.