Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To replace an element in an array:
indexOf()
method to get the index of the element.const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 if (index !== -1) { arr[index] = 'z'; } console.log(arr); // 👉️ ['z', 'b', 'c']
We used the
Array.indexOf
method to get the index of the array element with value a
.
We then replaced the element at that index with a new value.
indexOf
method returns -1
if it doesn't find an element with the supplied value.We check that the method didn't return an index of -1
to be sure that an
element with the specified value exists.
0
and the last an index of arr.length - 1
.Alternatively, you can use the array.splice()
method.
To replace an element in an array:
indexOf()
method to get the index of the element you want to
replace.Array.splice()
method to replace the element at the specific
index.const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 arr.splice(index, 1, 'z'); console.log(arr); // 👉️ [ 'z', 'b', 'c' ]
We passed the following 3 arguments to the Array.splice method:
We set the start
index to the index of the array element we want to replace.
delete count
of 1
, so the Array.splice()
method will remove the array element at the specified index and will add the provided third argument at the same index.In practice, we remove the array element at the specified index, and then insert a different value at the same index, so we end up replacing the array element.
An alternative approach is to use a basic for
loop.
To replace an element in an array:
array.length
times.for
loop.const arr = ['a', 'b', 'c']; for (let index = 0; index < arr.length; index++) { if (arr[index] === 'a') { arr[index] = 'z'; break; } } console.log(arr); // 👉️ ['z', 'b', 'c']
We used a basic for
loop to iterate over the array. On each iteration, we
check if the element is the one we want to replace.
Once we find and replace the element, we break out of the loop to avoid unnecessary work.
break
statement.An alternative solution is to not change the original array, but instead create
a new array containing the desired values. To achieve this we can use the
map()
method.
To replace an element in an array:
map()
method to iterate over the array.const arr = ['a', 'b', 'c']; const newArr = arr.map(element => { if (element === 'a') { return 'z'; } return element; }); console.log(newArr); // 👉️ ['z', 'b', 'c'] console.log(arr) // 👉️ ['a', 'b', 'c']
The function we passed to the Array.map method gets called with each element of the array.
The map()
method returns a new array, containing the values we return from the
callback function.
In the example, we replace the all array elements with value of a
setting them
to a value of z
.