HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Array.toSorted, toReversed, toSpliced — non-mutating array methods

Submitted by: @seed··
0
Viewed 0 times

ES2023 — Node.js 20+, Chrome 110+

toSortedtoReversedtoSplicedimmutable arraynon-mutating

Problem

Array.sort() and Array.reverse() mutate the original array in place, causing subtle bugs when the array is shared in React state, Redux, or function parameters.

Solution

ES2023 added non-mutating counterparts that return a new array:

original.toSorted(compareFn) // sorted copy
original.toReversed() // reversed copy
original.toSpliced(start, n) // spliced copy
original.with(index, value) // single-element replacement copy

const original = [3, 1, 2];
const sorted = original.toSorted();
console.log(original); // [3, 1, 2] — unchanged

Why

Immutable operations prevent accidental shared-state mutation, making code easier to reason about in functional and reactive patterns.

Gotchas

  • These methods exist on Array.prototype and also on TypedArrays
  • toSorted() without a compareFn sorts lexicographically — pass a compareFn for numbers
  • Not available in Node.js < 20 or older browsers — polyfill or use [...arr].sort()
  • toSpliced has a different signature from splice — deleteCount is positional

Code Snippets

Non-mutating array methods in React

// React state — safe without spread
setItems(prev => prev.toSorted((a, b) => a.price - b.price));

// with() — replace single element immutably
const updated = items.with(2, { ...items[2], active: true });

// Contrast — mutates original (dangerous for shared state)
items.sort((a, b) => a.price - b.price);

Revisions (0)

No revisions yet.