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
.