JavaScript immutable array methods: toSorted(), toReversed(), toSpliced(), with()

By

Tagged: JavaScript

Need to sort or reverse an array without mutating it? Use toSorted(), toReversed(), toSpliced(), and with() to get a new copy instead.

JavaScript has four array methods that return an updated copy instead of modifying the original array:

ChangeMutates the arrayReturns a changed copy
Sortsort()toSorted()
Reversereverse()toReversed()
Insert, remove, or replace itemssplice()toSpliced()
Replace one item at an indexitems[index] = valuewith()

The older sort(), reverse(), and splice() methods mutate the array in place, which is a classic source of subtle bugs. With these four methods, the original array stays untouched.

If you’re still getting comfortable with array methods, start with the free JavaScript course first. It covers arrays, callbacks, and transformation methods from the ground up.

The problem with mutation

Say you’ve got a list of scores and you sort them for a leaderboard:

const scores = [88, 42, 95, 71]
const leaderboard = scores.sort((a, b) => b - a)

console.log(scores)      // [95, 88, 71, 42]
console.log(leaderboard) // [95, 88, 71, 42]

scores changed too, because both variables point to the exact same array:

console.log(scores === leaderboard) // true

That’s fine if you wanted scores sorted everywhere. It turns into a sneaky bug the moment another part of your program still expects the original order.

For years, the workaround was to spread the array into a copy first:

const leaderboard = [...scores].sort((a, b) => b - a)

That works, and you’ll still see it in plenty of codebases. The newer methods just let you copy and update in a single call, so it’s immediately clear you don’t want to mutate the original.

Sort a copy with toSorted()

toSorted() works just like sort(), except it leaves the original array alone:

const scores = [88, 42, 95, 71]
const leaderboard = scores.toSorted((a, b) => b - a)

console.log(scores)      // [88, 42, 95, 71]
console.log(leaderboard) // [95, 88, 71, 42]

You get back a new array:

console.log(scores === leaderboard) // false

Comparator functions work the exact same way they do with sort(). Here’s how to sort numbers in ascending order:

const prices = [19, 5, 12]
const cheapestFirst = prices.toSorted((a, b) => a - b)

Don’t skip the comparator when you’re sorting numbers, because the default sort converts values to strings first:

const prices = [2, 11, 3]

console.log(prices.toSorted())              // [11, 2, 3]
console.log(prices.toSorted((a, b) => a - b)) // [2, 3, 11]

Check out how sort comparators work if you want more examples.

Sorting an array of objects by a property works the same way:

const products = [
  { name: 'Keyboard', price: 90 },
  { name: 'Mouse', price: 40 },
  { name: 'Display', price: 300 },
]

const byPrice = products.toSorted((a, b) => a.price - b.price)

products keeps its original order, while byPrice is a new array holding those same objects sorted by price.

Reverse a copy with toReversed()

When you want the items in reverse order without touching the original array, call toReversed():

const months = ['January', 'February', 'March']
const latestFirst = months.toReversed()

console.log(months)
// ['January', 'February', 'March']

console.log(latestFirst)
// ['March', 'February', 'January']

Before this method existed, you had to copy first:

const latestFirst = [...months].reverse()

Reach for toReversed() when you want a copy, and keep reverse() for cases where you deliberately want to flip the existing array in place.

Edit a copy with toSpliced()

toSpliced() is the copying version of splice(), and it takes the same arguments:

array.toSpliced(start, deleteCount, ...items)

Here’s how to replace one item:

const tasks = ['write', 'review', 'ship']
const updated = tasks.toSpliced(1, 1, 'test')

console.log(tasks)   // ['write', 'review', 'ship']
console.log(updated) // ['write', 'test', 'ship']

To insert items without removing anything, pass 0 as the delete count:

const tasks = ['write', 'ship']
const updated = tasks.toSpliced(1, 0, 'test')

console.log(updated) // ['write', 'test', 'ship']

To remove items without inserting anything, leave out the extra values:

const tasks = ['write', 'review', 'ship']
const updated = tasks.toSpliced(1, 1)

console.log(updated) // ['write', 'ship']

Negative indexes work here too and count backwards from the end:

const tasks = ['write', 'review', 'test', 'ship']
const updated = tasks.toSpliced(-2, 1, 'deploy')

console.log(updated)
// ['write', 'review', 'deploy', 'ship']

Here -2 lands on test, removes that one item, and inserts deploy in its place.

You can also drop everything from a starting index through the end of the array by omitting deleteCount:

const tasks = ['write', 'review', 'test', 'ship']
const updated = tasks.toSpliced(2)

console.log(updated) // ['write', 'review']

Watch out for passing undefined as the second argument, though. JavaScript converts it to 0, so toSpliced(2, undefined) removes nothing. Leave the argument out completely when you mean “remove the rest.”

There’s also a nice difference in what gets returned: splice() only gives you back the removed items, while toSpliced() returns the full updated array.

For other ways to delete items, see how to remove an item from an array.

Replace one item with with()

When you already know the index of the item you want to swap, with() is the cleanest way to do it:

const colors = ['red', 'green', 'blue']
const updated = colors.with(1, 'yellow')

console.log(colors)  // ['red', 'green', 'blue']
console.log(updated) // ['red', 'yellow', 'blue']

Negative indexes count backwards from the end here as well:

const colors = ['red', 'green', 'blue']
const updated = colors.with(-1, 'purple')

console.log(updated) // ['red', 'green', 'purple']

Pass an index outside the array bounds and JavaScript throws a RangeError:

const colors = ['red', 'green', 'blue']
colors.with(5, 'purple') // RangeError

That’s stricter than bracket assignment, which happily stretches the array and leaves empty slots past its old length.

Translate older code one operation at a time

If you’re cleaning up an existing codebase, each copying method maps cleanly onto an old copy-then-mutate snippet.

You can replace a copy-and-sort pattern like this:

const sorted = [...items].sort(compareItems)

with a single toSorted() call:

const sorted = items.toSorted(compareItems)

Same thing for copy-and-reverse. Turn this:

const reversed = [...items].reverse()

into:

const reversed = items.toReversed()

A copied splice() update like this:

const updated = [...items]
updated.splice(index, 1, replacement)

simplifies to:

const updated = items.toSpliced(index, 1, replacement)

And copying an array just to update one index:

const updated = [...items]
updated[index] = replacement

becomes:

const updated = items.with(index, replacement)

You drop the temporary variable, so there’s no copy sitting around for another line to mutate by mistake.

Just don’t replace in-place mutations blindly. Check first whether any other code depends on the original array changing.

Updating state without mutation

Because these methods return a new array reference, they fit UI state updates really well.

In React, for example, you can replace a single todo item right inside a state update:

setTodos(current => {
  const index = current.findIndex(todo => todo.id === changed.id)
  if (index === -1) return current

  return current.with(index, changed)
})

Or add a new item and move it to the front of a sorted list:

setTodos(current =>
  [...current, newTodo].toSorted((a, b) => b.createdAt - a.createdAt)
)

Because the state library receives a new array reference, it spots the change immediately without inspecting every item.

Build an immutable update from the item outward

When your array holds objects, copy the changed object first, then copy the array around it.

Start with a list of products:

const products = [
  { id: 1, name: 'Keyboard', price: 90, stock: 3 },
  { id: 2, name: 'Mouse', price: 40, stock: 8 },
]

Find the product you need to update:

const index = products.findIndex(product => product.id === 2)

Create the replacement object with object spread:

const changedProduct = {
  ...products[index],
  stock: products[index].stock - 1,
}

Then drop it into a copied array with with():

const updatedProducts = products.with(index, changedProduct)

The other product object stays shared between both arrays because it didn’t change, which is the standard immutable update pattern for nested data.

The copy is shallow

These methods only copy the array itself, not the objects inside it. Look at what happens if you modify an object directly:

const products = [
  { name: 'Keyboard', price: 90 },
  { name: 'Mouse', price: 40 },
]

const sorted = products.toSorted((a, b) => a.price - b.price)

sorted[0].price = 35

console.log(products[1].price) // 35

Both arrays still point to the same product objects. If you need to change an object without affecting the original array, copy that object too.

Chaining creates more than one copy

These methods chain together nicely:

const visibleProducts = products
  .filter(product => product.stock > 0)
  .toSorted((a, b) => a.price - b.price)
  .toReversed()

That’s easy to read, though every copying method in the chain creates another array.

For a small UI list, you won’t notice the cost. On a very large array in a hot path, skip any extra pass you don’t need. In this example, flipping the comparator lets you drop toReversed() completely:

const visibleProducts = products
  .filter(product => product.stock > 0)
  .toSorted((a, b) => b.price - a.price)

You still keep the original array unchanged, just with one fewer intermediate copy.

Common mistakes

Don’t forget that nested objects aren’t cloned, and that toSorted() still needs a numeric comparator so numbers aren’t compared as strings.

with() has a sneakier trap when you pass an index from a lookup that returned -1 for “not found”:

const index = products.findIndex(product => product.id === 99)
const updated = products.with(index, replacement)

Because -1 is a valid relative index, with() silently replaces the last item instead of failing.

Always check the index first:

const updated =
  index === -1
    ? products
    : products.with(index, replacement)

It’s an easy bug to miss because with(-1, value) is valid by design.

Also, the array you get back is still mutable:

const sorted = scores.toSorted((a, b) => b - a)
sorted.push(100)

The source array stays untouched, while sorted changes. These methods return a normal copy without freezing it.

When mutation is still fine

Copying isn’t free, because JavaScript has to allocate a new array and fill it with the items.

When an array is local, temporary, and owned by a single function, mutating it in place is totally fine:

function rankScores(input) {
  const scores = Array.from(input)
  scores.sort((a, b) => b - a)
  return scores
}

Nothing outside that function can ever see scores being mutated.

My advice is to use the copying methods at boundaries: function arguments, shared data, UI state, and cached results. Inside a small private scope, mutating a temporary array directly is fine when it makes the code clearer or avoids unnecessary copies.

Pick the method from the change

Use toSorted() or toReversed() when you’re only changing the order, with() when the array keeps the same length and one known position changes, and toSpliced() when you’re inserting, removing, or changing the length.

All four methods work in current browsers and modern Node.js releases (check compatibility if your project still supports an older runtime). You can find the other array methods in the JavaScript array guide.

When you need to split items into groups instead of changing the array, use Object.groupBy().

Want me to talk about your product? You can sponsor this site.

Related posts about js: