toSorted

2 snippets in JavaScript

JSJavaScript

Sorting

JS · Arrays
syntax
arr.sort(compareFn)
arr.toSorted(compareFn)
example
const nums = [40, 1, 5, 200];
// WRONG: default sort is lexicographic
console.log([...nums].sort());             // [1, 200, 40, 5]
// CORRECT: numeric sort
console.log([...nums].sort((a, b) => a - b)); // [1, 5, 40, 200]

// Non-mutating sort (ES2023)
const sorted = nums.toSorted((a, b) => b - a);
console.log(sorted); // [200, 40, 5, 1]
console.log(nums);   // [40, 1, 5, 200] (unchanged)

Note sort() MUTATES the array and defaults to string comparison. Always pass a compare function for numbers. Use toSorted() for a non-mutating alternative.

Non-Mutating Alternatives (ES2023)

JS · Arrays
syntax
arr.toSorted(fn)
arr.toReversed()
arr.toSpliced(start, deleteCount, ...items)
arr.with(index, value)
example
const original = [3, 1, 4, 1, 5];

const reversed = original.toReversed();
console.log(reversed);  // [5, 1, 4, 1, 3]

const replaced = original.with(2, 99);
console.log(replaced);  // [3, 1, 99, 1, 5]

console.log(original);  // [3, 1, 4, 1, 5] (untouched)

Note These return new arrays, leaving the original unchanged. Ideal for immutable state patterns (React, Redux, etc).