How to get indexOf nested array in any array?

48 views Asked by At

In Cocos TypeScript (I'm using the Cocos Creator 3.8 game engine), I have an array "foo". I also have arrays nested into foo such that foo = [[0, 0], [3, 2]];

However, when I attempt to call console.log(foo.indexOf([0, 0])) my program gives me a return value of -1. Is there something I'm doing wrong?

I was expecting to receive 0 from the console.log statement shown above.

4

There are 4 answers

0
Ricudo On BEST ANSWER

It won't work. Array is reference type, so even if both arrays have same values inside, they have different references in memory, so they are never equal. If you want to find array with the same values you have to compare values in these arrays or just stringify values before comparing:

index = foo.findIndex(item => JSON.stringify(item) === JSON.stringify([0, 0]));
1
Brent On

That is because you are trying to find something by reference and by typing a new [0,0] in the indexOf, you are creating a new reference and thus they don't match because its not the same reference to the array value at index 0.

When using primatives like a number or Boolean, they use value not reference.

0
XH栩恒 On

If you check the documentation from mdn here, they mention

The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN.

Now you know how they do the comparison behind the scene, when you try to do [0,0] === [0,0] you will get false. This is because it checks the reference instead of the value of array. 2 arrays of same value are not equal in JS

because everything in javascript is an object and arrays are also objects therefore instead of comparing the values or number of elements , it checks the reference of those array which is different that's why it returned false in both the cases

There are a few methods you can adopt to compare the arrays:

  1. first compare the array length and then the elements of the arrays
  2. Use lodash to compare arrays
0
Eric Leow Yu Quan On

As previous answers have mentioned, indexOf checks based on reference, so passing in another array as input will not give you the correct result because it has a different memory address from what you instantiated earlier.

A way to achieve what you want is to use toString() which will then get it to compare based on its value. An example snippet to achieve what you want is here:

const arr = [[0, 0], [1, 1]]
console.log(arr.indexOf([1, 1])) // prints -1
console.log(arr.map((element) => element.toString()).indexOf([1, 1].toString())) // prints 1