0

I spent the last hour and a half trying to find a bug in my code, when I finally realized that this JavaScript code:

[[1, 2], [3, 4]].indexOf([1, 2]);

returns -1, even though something such as [1, 2, 3].indexOf(1); correctly returns 0...

Why does this happen, and how can I find the correct index of the subarray?

2 Answers2

1

The indexOf takes only primitive arguments and you cannot match:

[1, 2] == [1, 2]

Which obviously gives false.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

You could iterate the array and check every item of the pattern and return the index.

function getIndexOf(array, pattern) {
    var index = -1;
    array.some(function (a, i) {
        if (a.length !== pattern.length) {
            return false;
        }
        if (a.every(function (b, j) { return b === pattern[j]; })) {
            index = i;
            return true;
        }
    });
    return index;
}

console.log(getIndexOf([[1, 2], [3, 4], [7, 8]], [7, 8]));

Another way with JSON and indexOf.

function getIndexOf(array, pattern) {
    return array.map(function (a) { return JSON.stringify(a); }).indexOf(JSON.stringify(pattern));
}

console.log(getIndexOf([[1, 2], [3, 4], [7, 8]], [7, 8]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392