Categories
JavaScript Answers

How to Replace an Item in a JavaScript Array?

Spread the love

Sometimes, we may want to replace an item in a JavaScript array.

In this article, we’ll look at how to replace an item in a JavaScript array.

Array.prototype.indexOf and Assignment

We can use the JavaScript array’s indexOf method to find the index of a given value in an array.

Then we can use the index to assign the new value to that index.

For instance, we can write:

const arr = [523, 353, 334, 31, 412];
const index = arr.indexOf(353);
if (index !== -1) {
  arr[index] = 1010;
}
console.log(arr)

We call arr.indexOf with the value we’re looking for.

It’ll return the index of the first instance of a value if it exists or -1 otherwise.

So if index isn’t -1, then we can replace the value at the given index with a new one by assigning it as we did in the if block.

So arr is now:

[523, 1010, 334, 31, 412]

Array.prototype.map

We can use the map method to return a new array with the entries of the existing array mapped to new values.

To use this to replace one or more instance of a value, we can write:

const arr = [523, 353, 334, 31, 412];
const mapped = arr.map(a => a == 353 ? 1010 : a)
console.log(mapped)

We call map with a callback that checks if a , which is the value being iterated through is 353.

If it is, then we replace that with 1010.

Otherwise, we just return the existing value.

So mapped is now:

[523, 1010, 334, 31, 412]

Array.prototype.indexOf and Array.prototype.splice

We can also use the JavaScript array’s splice method to replace a value at the given index with a new one.

For instance, we can write:

const arr = [523, 353, 334, 31, 412];
const index = arr.indexOf(353);
if (index !== -1) {
  arr.splice(index, 1, 1010);
}
console.log(arr)

We get the index of 353 the same way.

But instead of assigning the value, we call splice with the index of the element to remove.

1 in the 2nd argument means we remove 1 element.

And the 3rd argument is the value we replace the item with.

So arr is the same as the first example.

Conclusion

We can use array methods to replace an object at the given index with another value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *