Javascript 数组包含/包含子数组

2022-01-25 00:00:00 arrays contains include javascript indexof

我需要检查一个数组是否包含另一个数组.子数组的顺序很重要,但实际偏移量并不重要.它看起来像这样:

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

所以我想知道 master 是否包含 sub 类似的东西:

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?

推荐答案

fromIndex 参数

此解决方案的特点是对索引进行封闭,以便在数组中搜索元素的起始位置.如果找到子数组的元素,则搜索下一个元素以递增的索引开始.

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

相关文章