Categories
JavaScript Answers

How to remove array element by value with JavaScript?

Spread the love

Sometimes, we want to remove array element by value with JavaScript.

In this article, we’ll look at how to remove array element by value with JavaScript.

How to remove array element by value with JavaScript?

To remove array element by value with JavaScript, we use the indexOf method.

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 with 'red' to get the index of 'red' in arr.

Then we call splice to remove 'red' by calling it with index and 1.

Conclusion

To remove array element by value with JavaScript, we use the indexOf method.

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 *