Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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/


Solution 2:

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

Solution 3:

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

Post a Comment for "Finding Sub-array Within Array"