Search code examples
javascriptarraysarray-splice

Remove array from inside array based on index in JS


I have an array which looks like:-

[[0,1], [0,2], [0,3], [1,1], [1,2]...]

I am looking to remove one of the arrays from this array based on the indexOf() but I keep getting a value of -1, which removes the last item from the array when I try the following code:-

array = [[0,1], [0,2], [0,3], [1,1], [1,2]];
console.log('Removed value', array.splice(array.indexOf([0,3]), 1));
console.log('Result', array);

would somebody be able to point me in the right direction to help solve this issue I am having?

Thank you in advance.


Solution

  • You can't use indexOf because when you declare [0,3] in array.splice(array.indexOf([0,3]), 1)) you're creating a new array and this new object is not inside your array (but rather another array that has the same values).

    You can use findIndex instead as follows (example):

    array.findIndex(x => x[0] === 0 && x[1] === 3)
    

    this will return 2 - now you can use it to delete:

    array.splice(2, 1)