Numeric ascending order
Ordering numeric data such as scores, prices, or timestamps with (a, b) => a - b.
JavaScript · Function
Array.prototype.sort() sorts an array in place and returns the same array. By default it compares string representations in UTF-16 order; pass a comparator for custom ordering.
sort() rearranges an array's existing elements in place and returns that same array. With no comparator, it compares string representations in UTF-16 code-unit order; with a comparator, its numeric result determines which element comes first.
sort()
sort(compareFn)| Name | Type | Description |
|---|---|---|
compareFn | function | Optional function receiving two elements and returning a number that determines their relative order. |
The reference to the original array, now sorted.
toSorted() instead when preserving the original array is required.const scores = [10, 2, 30];
scores.sort((a, b) => a - b);
console.log(scores); // [2, 10, 30]Provide a numeric comparator when sorting numbers so their values determine ascending order.
Ordering numeric data such as scores, prices, or timestamps with (a, b) => a - b.
Arranging records by a selected field with a comparator that compares the field values.
Ordering text according to a locale by supplying a comparator such as one produced by Intl.Collator.
sort() mutate the original array?sort() mutates the array and returns a reference to that same, now-sorted array. It does not create a separate array.
Follow-up: How would you sort without mutation? Use toSorted(), which returns a sorted copy while leaving the source array unchanged.
sort() use by default?Without compareFn, elements are converted to strings and compared in UTF-16 code-unit order. Therefore, the default behavior is not numeric ordering for ordinary arrays.
Follow-up: How do you sort numbers ascending? Pass (a, b) => a - b as the comparator.
compareFn control ordering?A comparator receives two defined elements, a and b. A negative result places a first, a positive result places b first, and zero or NaN treats them as equal.
Follow-up: What happens to undefined elements? They are placed at the end without calling the comparator for them.
Array.prototype.toSorted()Array.prototype.reverse()Intl.Collator