Javascript indexOf for an array of arrays not finding array Javascript indexOf for an array of arrays not finding array arrays arrays

Javascript indexOf for an array of arrays not finding array


That's because you're searching for a different object. indexOf() uses strict equality comparisons (like the === operator) and [3, 0] === [3, 0] returns false.

You'll need to search manually. Here's an example using a more generic indexOf() function that uses a custom comparer function (with an improvement suggested by @ajax333221 in the comments):

// Shallow array comparerfunction arraysIdentical(arr1, arr2) {    var i = arr1.length;    if (i !== arr2.length) {        return false;    }    while (i--) {        if (arr1[i] !== arr2[i]) {            return false;        }    }    return true;}function indexOf(arr, val, comparer) {    for (var i = 0, len = arr.length; i < len; ++i) {        if ( i in arr && comparer(arr[i], val) ) {            return i;        }    }    return -1;}var tw = [[3, 0], [11, 0], [3, 14], [11, 14]];alert( indexOf(tw, [3, 0], arraysIdentical) ); // Alerts 0


Arrays are objects. [3, 0] does not equal [3, 0] as they are different objects. That is why your inArray fails.


Because you're comparing two difference instance of array. Comparing objects returns true only if they're the same instance, it doesn't matter if they contain the same data.

In your case, you could use this approach:

var tw = [[3, 0], [11, 0], [3, 14], [11, 14]];if (~tw.join(";").split(";").indexOf(String([3, 0]))) {    // ...}

Or something more ortodox like:

if (tw.filter(function(v) { return String(v) === String([3, 10]) })[0]) {   // ...}

Where the condition can be adjusted depends by the content of the arrays.