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?

5
  • 5
    Try this in your console: [1] == [1]. It's for the same reason. Commented Jan 20, 2020 at 11:48
  • 2
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…: “If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory. Commented Jan 20, 2020 at 11:48
  • 1
    check out Array#findIndex for this. Commented Jan 20, 2020 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]));. Commented Jan 20, 2020 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]; }); });). Commented Jan 20, 2020 at 11:52

1 Answer 1

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

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

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.