how to remove an array element in array of array in js?

Viewed 49

I am trying to remove an array element from an array of arrays. but i am not able to do it.

JS code:

var blueTiles = [];
blueTiles.push([1, 1]);
blueTiles.push([2, 2]);
blueTiles.push([3, 3]);

var removeCoord = [2, 2];

var index = blueTiles.indexOf(removeCoord);
if (index > -1) blueTiles.splice(index, 1);

but here i am trying to get position of array element in blueTile array ans remove using splice function. but i am getting index value as -1 even though [2, 2] exists in it

please help me in solving this.

1 Answers

Use this as your index (checks all array elements against the remoceCoord elements)

var index = blueTiles.findIndex(x=>x.every((y,i)=>y===removeCoord[i]))

var blueTiles = [];
blueTiles.push([1, 1]);
blueTiles.push([2, 2]);
blueTiles.push([3, 3]);

var removeCoord = [2, 2];

var index = blueTiles.findIndex(x => x.every((y, i) => y === removeCoord[i]))
if (index > -1) blueTiles.splice(index, 1);

console.log(blueTiles)

Related