1

I am trying to find the index of an array inside another array in Javascript, as below:

const piece = [5, 10];
const array = [[5, 10], [5, 11]];

//Using indexOf
console.log(array.indexOf(piece));

//Using findIndex
console.log(array.findIndex(function(element) {
  return element == piece;
  }));

I'm expecting these to return a 0 as that is the index where my "piece" is inside the larger array, but both methods return -1

Any ideas why this is happening? And if there is a different way for me to do this?

Thanks.

2
  • 3
    They are different arrays that happen to have the same numbers, but still different arrays. Commented Jan 6, 2022 at 17:58
  • Please follow the link to see a solution. stackoverflow.com/a/34170710/1635742 Commented Jan 6, 2022 at 18:04

3 Answers 3

5

To compare the actual values you can use the JSON.stringify() method:

piece = [5, 10];
array = [[5, 10], [5, 11]];

//Using findIndex
console.log(array.findIndex(function(element) {
    return JSON.stringify(element) == JSON.stringify(piece);
    }));

Sign up to request clarification or add additional context in comments.

Comments

1

You are comparing objects (arrays) that were created each on their own, so they are not the same objects. If you want, you can compare each of the integers inside the arrays, and when also the array lengths match, you can conclude they are the "same":

piece = [5, 10];
array = [[5, 10], [5, 11]];

//Using findIndex
console.log(array.findIndex(function(element) {
  return element.length === array.length 
      && element.every((val, i) => val == piece[i]);
}));

Comments

0

Arrays in JavaScript are not compared by value, but by reference. So if you have arrays a and b like this:

const a = [1, 2];
const b = [1, 2];

When you compare them using ==, or === then their references are compared, not values. So this console.log(a == b), or console.log(a === b) will print false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.