JavaScript: Update/Replace a Specific Element in an Array

Updated: March 22, 2023 By: Khue Post a comment

This quick and straightforward article shows you a couple of different ways to update or replace a specific element in an array in modern JavaScript.

Using array[index] syntax

You can directly access an element in an array using its index and update its value:

const games = [
  'Elden Ring',
  'GTA 5',
  'Horizon Forbidden West'
];

// Update the second element whose index is 1
games[1] = 'Pokemon Go';
console.log(games);

Output:

[ 'Elden Ring', 'Pokemon Go', 'Horizon Forbidden West' ]

If you don’t know the index of an element but already know its value, you can its index by using the indexOf() method. The example below will update the element whose value is Dog:

const animals = ['Chicken', 'Elephant', 'Dog', 'Cat']

const indexOfDog = animals.indexOf('Dog')
if(indexOfDog > -1) {
  animals[indexOfDog] = 'Dragon'
}

console.log(animals)

Output:

[ 'Chicken', 'Elephant', 'Dragon', 'Cat' ]

Using the splice() method

The splice() method allows you to add or remove elements from an array. You can use it to replace an element by specifying the index, the number of elements to remove (which is 1 in this case), and the new element to add.

Example:

let myArray = [10, 20, 30, 40, 50];

// Replace the 4th element (whose index = 3) with 2500
myArray.splice(3, 1, 2500); 
console.log(myArray);

Output:

[ 10, 20, 30, 2500, 50 ]

That’s it. Happy coding!