2

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.

1

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Consider nixing delete in favor of splice. delete replaces the item at index 2 with undefined. I don't think that is what the OP wanted.
1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.