Web Nexus
Web Nexus

Reputation: 1158

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.

Upvotes: 2

Views: 75

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

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)

Upvotes: 5

bigh_29
bigh_29

Reputation: 2633

If it is OK to remove every occurrence of [0,3], then consider Array.filter combined with array destructuring of the lambda arguments. It offers a slightly leaner syntax than the other solutions.

const input = [
    [0,1],
    [0,2],
    [0,3],
    [1,1],
    [1,2]
];


const result = input.filter(([x,y]) => !(x==0 && y==3));
console.log('Result=', result);

Upvotes: 1

ecc521
ecc521

Reputation: 657

To explain why your solution will not work:

Comparison operators only work for values not passed by a reference. When dealing references, comparison operators always return false, unless the two references point to the same object. (See this on MDN)

An example:

a = [0,1]
b = a
b === a //true. a and b point to the same array.
a === [0,1] //false. a points to a different array than [0,1]
b[0] = 2
a[0] //2 - b points to the same array as a

To give you a solution (borrows from here)

//Function to compare the values inside the arrays, and determine if they are equal. 
//Note: does not recurse.
function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

array = [[0,1], [0,2], [0,3], [1,1], [1,2]];
//Find the index where x has the same values as [0,3]
array.findIndex(x => arraysEqual(x, [0,3])) //2

Upvotes: 0

Related Questions