如何返回正确的数组,该数组包括第二个数组中的所有值



假设有两个数组。

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

您可以使用filterevery,如下所示。

或者您可以使用filtersome以及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);

相关内容

最新更新