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?

QCD_IS_GOOD
  • 435
  • 7
  • 22
  • indexOf returns -1 if the value pair does not exist. – mattdevio Dec 09 '15 at 04:15
  • 1
    Possible Duplicate of [indexOf syntax for multidimensional arrays?](http://stackoverflow.com/questions/1427640/indexof-syntax-for-multidimensional-arrays) or better [Javascript 2d array indexof](http://stackoverflow.com/questions/24943200/javascript-2d-array-indexof) – Tushar Dec 09 '15 at 04:16

2 Answers2

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;
}
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
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.

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101