Categories
JavaScript Answers

How to remove array element by value with JavaScript?

Spread the love

To remove array element by value with JavaScript. we use the indexOf and splice methods.

For instance, we write

const arr = ["orange", "red", "black", "white"];
const index = arr.indexOf("red");
if (index >= 0) {
  arr.splice(index, 1);
}

to call arr.indexOf to get the index of the first instance of 'red' in arr.

Then we check if index is bigger than 0 to check if it’s found.

If it is, then we call splice with index and 1 to return the item in arr at index.

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 *