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.