transformation
Array.prototype.sort
Sorts the array in place and returns the same array; without a compareFn elements are coerced to strings and sorted lexicographically. Reach for it when you need ordered data — but always pass a compareFn for numbers.
arr.sort([compareFn]) Parameters
| Parameter | Purpose |
|---|---|
| compareFn(a, b) | Return <0 to place a first, >0 to place b first, 0 to keep order |
| (no compareFn) | Elements are converted to strings and compared by UTF-16 code units |
Examples
console.log([10, 1, 21, 2].sort()); Logs: [1, 10, 2, 21] (string sort — beginner gotcha!)
console.log([10, 1, 21, 2].sort((a, b) => a - b)); Logs: [1, 2, 10, 21] (numeric ascending)
const arr = [3, 1, 2]; arr.sort(); console.log(arr); Logs: [1, 2, 3] — sort MUTATES the original array
console.log([3, 1, 2].toSorted()); Logs: [1, 2, 3] and leaves the original untouched (ES2023 non-mutating alternative)
Gotcha
MUTATES the original array AND returns it — a common beginner bug. Default sort is lexicographic, so [10, 2] sorts as [10, 2]. Use `toSorted()` (ES2023) for a non-mutating copy.
Related methods
Array.prototype.reverse
Reverses the order of elements in place and returns the same (mutated) array. Reach for it when you truly want to reverse the source; otherwise use toReversed().
Array.prototype.slice
Returns a shallow copy of a portion of the array from start (inclusive) to end (exclusive) without modifying the source. Reach for it to extract a range or to clone an array (`arr.slice()`).
Array.prototype.concat
Returns a new array formed by joining the source with the provided arrays and/or values (one level of spread). Reach for it to merge arrays without mutating any of them.
Array.prototype.flat
Returns a new array with all sub-array elements concatenated up to the specified depth (ES2019). Reach for it to unnest arrays of arrays without a manual reduce.
Array.prototype.flatMap
Maps each element with a callback, then flattens the result by one level (ES2019). Reach for it when a mapper naturally returns arrays and you want a single flat list back.