假设有两个数组。
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
我想要的是,如果arrayyTest中的所有值都包含在MotherArray[i]
中
我试过
let MotherArray = [[30, 1, 2, 3, 4, 5, 6],[5, 6, 7, 8, 9],[7, 8, 9],];
let arraytoTest = [5, 6];
let result = MotherArray.includes(arraytoTest)
console.log(result);
但我认为这不是正确的方法。我也找到了array.every((,但我认为我的用法不正确。
我想要的是,我想要返回MotherArray[0],MotherArray[1]
,在这个特定的例子中是[[30, 1, 2, 3, 4, 5, 6],[5, 6, 7, 8, 9]]
因为5和6包括在这两个阵列内部。
您可以将array.filter()
与array.every()
组合使用
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
let found = MotherArray.filter(childArray => arraytoTest.every(num => childArray.includes(num)));
console.log(found);
我想这就是您想要的;母阵列上的filter
和您正在测试的阵列的every
的组合。
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
let result = MotherArray.filter(arr => arraytoTest.every(x => arr.indexOf(x)>-1));
console.log(result);
您可以使用filter
和every
,如下所示。
或者您可以使用filter
和some
以及negative
条件,如filter(x => !arraytoTest.some(y => !x.includes(y)))
。我认为some
应该是efficient
,因为
some()
方法对数组中的每个元素执行一次callback
函数,直到找到callback
返回truthy
值的元素。
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
let result = MotherArray.filter(x => arraytoTest.every(y => x.includes(y)));
console.log(result);
let result2 = MotherArray.filter(x => !arraytoTest.some(y => !x.includes(y)));
console.log(result2);