Javascript array contains/includes sub array

Victor Axelsson picture Victor Axelsson · Dec 8, 2015 · Viewed 17k times · Source

I need to check if an array contains another array. The order of the subarray is important but the actual offset it not important. It looks something like this:

var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]; 

var sub = [777, 22, 22]; 

So I want to know if master contains sub something like:

if(master.arrayContains(sub) > -1){
    //Do awesome stuff
}

So how can this be done in an elegant/efficient way?

Answer

Nina Scholz picture Nina Scholz · Dec 8, 2015

With a little help from fromIndex parameter

This solution features a closure over the index for starting the position for searching the element if the array. If the element of the sub array is found, the search for the next element starts with an incremented index.

function hasSubArray(master, sub) {
    return sub.every((i => v => i = master.indexOf(v, i) + 1)(0));
}

var array = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];

console.log(hasSubArray(array, [777, 22, 22]));
console.log(hasSubArray(array, [777, 22, 3]));
console.log(hasSubArray(array, [777, 777, 777]));
console.log(hasSubArray(array, [42]));