typescriptcocoscreator

How to get indexOf nested array in any array?


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.


Solution

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