Javascript array contains/includes sub array Javascript array contains/includes sub array arrays arrays

Javascript array contains/includes sub array


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]));


Just came up with quick thought , but efficiency depends on size of the array

var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];var sub = [777, 22, 22];if ((master.toString()).indexOf(sub.toString()) > -1 ){    //body here}


var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]; var sub = [777, 22, 22]; console.log(master.join(',').includes(sub.join(',')))//true

You can do this by simple console.log(master.join(',').includes(sub.join(','))) this line of code using include method