1

I have simple nested array, like:

var arr = [[75.0], [65.0]] ;

and when I do:

arr.indexOf( [75.0] );

I expect 0, but I get -1, what gives?

Kresimir Pendic
  • 3,597
  • 1
  • 21
  • 28
  • 5
    Try this in your console: `[1] == [1]`. It's for the same reason. – Federico klez Culloca Jan 20 '20 at 11:48
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality_operators: _“If both operands are objects, then JavaScript compares internal references which are equal **when operands refer to the same object in memory.**”_ – 04FS Jan 20 '20 at 11:48
  • 1
    check out [Array#findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) for this. – Thomas Jan 20 '20 at 11:50
  • 1
    `indexOf` uses an `===` match to see if what you provide matches what's in the array. No two separate arrays are `===` to each other (`[75.0] === [75.0]` is `false`), even if the arrays have the same contents. To find the index of an *equivalent* array, you'll need to use `findIndex` and provide a callback that checks that the arrays have the same contents, for instance (assumign `target` is the array to find): `const index = arr.findIndex(entry => entry.length === target.length && entry.every((value, index) => value === target[index]));`. – T.J. Crowder Jan 20 '20 at 11:52
  • 1
    (Or in ES5 with a `findindex` polyfill: `var index = arr.findIndex(function(entry) { return entry.length === target.length && entry.every(function(value, index) { return value === target[index]; }); });`). – T.J. Crowder Jan 20 '20 at 11:52

1 Answers1

0

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf :

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

There is the problem. In your example, you have an array of arrays. Comparing with === operator means that for it to evaluate to true, it has to be the same array object. Clearly it is a different object so it is not found from the array.

You need to use Array.find() instead where you can provide the testing function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

teroi
  • 1,087
  • 10
  • 19