Finding Sub-array within Array

I have the Array

array = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];

and I want to find the index of the sub array

[1, 2, 3, 4]

So it should return the value 0
but every time I try to do this, it returns -1

Here is what i tried:

array.indexOf(1, 2, 3, 4);

I know this is because the subarray i am searching for has commas in it.
how can i fix this

Answers:

Answer

Here is a quick and dirty solution which compares the arrays as strings:

var array = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];

var target = [9, 10, 11, 12].toString();
for(var i=0; i<array.length; i++) {
   if(target === array[i].toString()) break;
}

if(i >= array.length) {
    console.log("not found");
} else {
    console.log("found at index " + i);
}

http://jsfiddle.net/jMfwQ/

Answer

The issue is that when javascript uses == to compare arrays it doesnt work as expected. You will have to build your own array equality checker (see How to check if two arrays are equal with JavaScript?). Then loop through the array and check per sub element if it is equal to the one you are trying to find

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;

    // If you don't care about the order of the elements inside
    // the array, you should sort both arrays here.

    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
}

var haystack = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
var needle = [1, 2, 3, 4];
var i = 0;

for(var sub in haystack) {
    if(array_equal(sub, needle)) { // found it
        return i;
    }
    i++;
}

if(i >= haystack.size) //didn't find it
    i = -1;

return i; //return the index of the found needle-array
Answer

a dead-simple string-matching implementation that uses only native methods and no variables:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
 .map( /./.test, RegExp( "^"+ [9, 10, 11, 12]+"$"  )).indexOf(true); // === 2

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.