How to Replace an Item in a Javascript Array

Array operations are very common when coding in Javascript, and since the introduction of es6 and going forward, we have multiple ways of achieving the required results. So how do we replace an item in Array with Javascript?

We can use two approaches, the mutable, Array.splice() approach, or the immutable, Array.splice() with the spread operator approach. Choosing between the two approaches depends on the context and the environment you’re working in.

Replace an Item in an Array using Array.splice()

The first approach is quite simple, we just mutate the same array. The Array.splice() method is used to extract items from an array, but also it supports the option of replacing the extracted items with new ones:

// example array
const array = 'Hello, my name is Inigo Montoya, you killed my father, prepare to die!'.split(' ')

// grab the index we want to change
const index = array.indexOf('Inigo')

// Mutable approach to replacing the item
array.splice(index, 1, 'Carlos')

// convert array to string
// "Hello, my name is Carlos Montoya, you killed my father, prepare to die!"
console.log(array.join(' '));

Replace an Item in an Array using Spread Operator

The second approach consists of creating a new array from:

  • The first part of the original array, from 0 to the desired index to change.
  • The new value.
  • The rest of the array items, from the index we want to change + 1 until the end.
// example array
let array = 'Hello, my name is Inigo Montoya, you killed my father, prepare to die!'.split(' ')

// grab the index we want to change
const index = array.indexOf('Inigo')

// Immutable approach to replacing the item
array = [
  ...array.slice(0, index),
  'Carlos',
  ...array.slice(index + 1)
]

// convert array to string
// "Hello, my name is Carlos Montoya, you killed my father, prepare to die!"
console.log(array.join(' '));

We used the Array.slice() method to create a copy of the first part of the array, and we did the same thing fo the second part. Then, we use the spread operator inside the array literal to spread these items into the new one.

This approach is used more in the ReactJs/functional world. You can find other operations that we can perform with this approach here.