1

I have the following code:

alert( [[0,1],[1,0]].indexOf([0,1]) );

And even though the array [0,1] is an element of the two-dimensional array, I get a value of '-1' returned. What have I done wrong in life?

2

2 Answers 2

5

It doesn't find your element because [0, 1] and [0, 1] are not equal in the same way that 4 and 4 are.

console.log(4 === 4); // true
console.log([0, 1] === [0, 1]); // false

When you do an equality check for things with a type of object, then Javascript uses what's known as reference equality. It checks whether the two objects are actually the same instance.

var a = [0, 1];
var b = [1, 0];
var arr = [a, b];

console.log(arr.indexOf(a)); // 0
console.log(a === arr[0]); // true

Alternatively you can write your own search function using a deep equality check.

function deepSearch(arr, element) {
  for(var index = 0; index < arr.length; index++) {
    if(deepEqual(arr[index], element)) {
      return index;
    }
  }

  return -1;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Short answer: Because [0,1] === [0,1] is false.

According to .indexOf documentation,

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

You can use a trick and serialize your subarrays and target item.
It works, because [0,1] !== [0,1], but "[0,1]" === "[0,1]":

Array.prototype.indexOfForArrays = function(search)
{
  var searchJson = JSON.stringify(search); // "[0,1]"
  var arrJson = this.map(JSON.stringify); // ["[3,4]", "[0,1]", "[1,0]"]

  return arrJson.indexOf(searchJson);
};

document.body.innerText = [[3,4], [0,1], [1,0]].indexOfForArrays([0,1]); 

There are some other methods. This Stackoverflow question may be useful.

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.