Numeric ordering with a comparator
You need a list ordered by numeric value.
JS Puzzles · Const
Array.prototype.sort() rearranges an array in place and returns the same array. Without a comparator, it compares string representations by UTF-16 code units, so numeric values require an explicit numeric comparator.
Calling sort() rearranges the existing array and returns that same array. With no comparator, defined elements are converted to strings and compared by UTF-16 code units, so numeric-looking values may sort lexicographically rather than numerically; undefined elements go last.
arr.sort(compareFn)| Name | Type | Description |
|---|---|---|
compareFn | function | undefined | Optional comparator receiving two elements and returning a negative, positive, or zero number to determine their order. |
The same array reference, after its elements have been sorted.
const values = [10, 2, 1];
values.sort();
console.log(values); // [1, 10, 2]
values.sort((a, b) => a - b);
console.log(values); // [1, 2, 10]Without a comparator, numeric values are compared as strings; provide a numeric comparator for ascending numeric order.
You need a list ordered by numeric value.
You need a sorted result while preserving the input array.
You need deterministic ordering for records with equal sort keys.
With no argument, sort converts non-undefined elements to strings and compares their UTF-16 code units. Therefore, [10, 2, 1] sorts as [1, 10, 2], not numeric ascending order.
Follow-up: How would you sort numbers ascending? Pass (a, b) => a - b as the comparator.
The method sorts the array in place and returns a reference to that same, now-sorted array. It does not produce an independent array.
Follow-up: How can you avoid mutation? Use toSorted(), which returns a sorted copy.
A comparator receives two elements and should return a negative number when the first belongs before the second, a positive number when it belongs after it, or zero when their order is equivalent. Omitting it selects the string-based default.
Follow-up: What happens to undefined elements with a comparator? They are placed at the end without calling the comparator for them.
Array.prototype.toSorted()Array.prototype.map()TypedArray.prototype.sort()