Array.prototype.sort
array.sort(compareFn)Sort the array in place. The default comparison uses string conversion, not numeric value.
| Parameter | Description |
|---|---|
compareFn | Optional comparator. Return a negative number if a should come before b, a positive number if a should come after b, and 0 if they are equal. If omitted, elements are compared as strings. |
Returns: The same array object, now reordered.
Throws
TypeError— Thrown if compareFn is provided and is not callable.
- sort() mutates the original array. Keep a copy if you still need the earlier order.
- The default string order is rarely what you want for numbers or for ISO dates that are not zero-padded consistently.
const nums = [10, 2, 1];
console.log(JSON.stringify([...nums].sort()));
console.log(JSON.stringify([...nums].sort((a, b) => a - b)));
const original = [3, 1, 2];
const same = original.sort((a, b) => a - b);
console.log(JSON.stringify(original), same === original);Expected output
[1,10,2]
[1,2,10]
[1,2,3] trueRelated: toSorted