I have an array with length 9. I want to remove elem from array.
arr = [
[0, 0],
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[2, 2]
]
let elem = [2, 0];
let index = arr.indexOf(elem)
if (index !== -1) {
arr.splice(arr.indexOf(elem), 1)
}
console.log(arr)
Why my splice does not work?
It is not possible to use Array#indexOf
with another object reference than the same object reference. This means, if you have another array to check against, you need to iterate it element by element. For this, you could use Array#findIndex
and iterate all elements with Array#every
.
For splicing, you need the found index, and not to find another index, because you have it already.
var arr = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]],
elem = [2, 0],
index = arr.findIndex(a => a.every((v, i) => elem[i] === v));
console.log(index);
if (index !== -1) {
arr.splice(index, 1);
}
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }