Categories
JavaScript Answers

How to replace item in array with JavaScript?

Spread the love

To replace item in array with JavaScript, we can assign a new value directly.

For instance, we write

const items = [523, 3452, 334, 31, 57];

const index = items.indexOf(3452);

if (index !== -1) {
  items[index] = 1010;
}

to call items.indexOf to get the index of 3452.

Then we check if index isn’t -1.

If it’s not, then the item exists and we can assign a new value to it with

items[index] = 1010;

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 *