John
John

Reputation: 257

Can't remove element using splice

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?

Upvotes: 1

Views: 86

Answers (4)

StudioTime
StudioTime

Reputation: 23989

You can use .filter() instead: (more about .filter() here)

arr = [
  [0, 0],
  [0, 1],
  [0, 2],
  [1, 0],
  [1, 1],
  [1, 2],
  [2, 0],
  [2, 1],
  [2, 2]
]

let elem = [2, 0];
const newArray = arr.filter(item => !(item[0] === elem[0] && item[1] === elem[1]));

console.log(newArray)
.as-console-wrapper { max-height: 100% !important; top: 0; }

This simply checks if both parts of the array match, then reverses the result, so only those that DON'T match are returned

Not that it makes much difference nowadays but .filter() is also faster - Here's a test I ran on JSPerf

Upvotes: 1

protoproto
protoproto

Reputation: 2099

You can use JSON object to remove quickly a element:

arr = [
  [0, 0],
  [0, 1],
  [0, 2],
  [1, 0],
  [1, 1],
  [1, 2],
  [2, 0],
  [2, 1],
  [2, 2]
]

let elem = [2, 0];
var arrjson = arr.map(JSON.stringify);
var elemjson = [elem].map(JSON.stringify);
//console.log(arrjson); //console.log(elemjson); 
var index = arrjson.indexOf(elemjson[0]);
arrjson.splice(index,1);
//console.log(arrjson);
var arrresult = arrjson.map(JSON.parse);
console.log(arrresult);

Upvotes: 0

brk
brk

Reputation: 50326

You can use the filter function

arr = [
  [0, 0],
  [0, 1],
  [0, 2],
  [1, 0],
  [1, 1],
  [1, 2],
  [2, 0],
  [2, 1],
  [2, 2]
]
let m = [];
let elem = [2, 0];
let __j = elem.toString();

let k = arr.filter(function(item) {
  let __i = item.toString();
  return __i !== __j
})


console.log(k)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

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; }

Upvotes: 3

Related Questions