JavaScript, how to replace an item of an array

By

Learn how to replace an item in a JavaScript array: if you know its index, a simple assignment swaps the value, otherwise find the index first.

~~~

Given an array, if you know the index of an item you can replace its content using a simple assignment:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 2

items[i] = '--NEW-ITEM--'

console.log(items)
//[ 'a', 'b', '--NEW-ITEM--', 'd', 'e', 'f' ]

This mutates the array in place. Notice it works with const: we’re not reassigning the variable, we’re changing the content of the array it points to.

splice() can do the same job. Pass it the index, how many items to remove, and the new item:

const items = ['a', 'b', 'c']
items.splice(1, 1, 'z')

console.log(items) //[ 'a', 'z', 'c' ]

It’s more useful when you want to swap one item for several at once, since you can pass more than one replacement. For a one-to-one swap, the plain assignment is clearer.

What if you don’t know the index?

Then you need to find the index of the item in the array first. findIndex() does it:

const drinks = ['coffee', 'tea', 'water']

const i = drinks.findIndex((drink) => drink === 'tea')
drinks[i] = 'juice'

console.log(drinks)
//[ 'coffee', 'juice', 'water' ]

The pitfall: the item is not in the array

findIndex() returns -1 when nothing matches. And if you assign at index -1, JavaScript does not throw an error. It quietly adds a -1 property to the array object:

const drinks = ['coffee', 'tea']
const i = drinks.findIndex((drink) => drink === 'wine') //-1

drinks[i] = 'juice'

console.log(drinks)
//[ 'coffee', 'tea', '-1': 'juice' ]

The length is still 2 and no real item was replaced. This kind of silent bug is hard to spot later. Check for -1 before assigning:

if (i !== -1) {
  drinks[i] = 'juice'
}

Replacing without mutating the array

Sometimes you don’t want to touch the original array, for example when updating React state. In that case, build a new array with map():

const drinks = ['coffee', 'tea', 'water']

const updated = drinks.map((drink) => (drink === 'tea' ? 'juice' : drink))

console.log(updated) //[ 'coffee', 'juice', 'water' ]
console.log(drinks)  //[ 'coffee', 'tea', 'water' ]

Each item passes through the function. The one that matches is replaced, the others are returned as they are. The original array stays intact.

If you already know the index, with() does the same in one call:

const drinks = ['coffee', 'tea', 'water']

const updated = drinks.with(1, 'juice')
//[ 'coffee', 'juice', 'water' ]

with() returns a copy of the array with the item at that index replaced. It’s a recent addition (ES2023), available in all modern browsers and in Node.js 20 and up.

~~~

Related posts about js: