迭代数组的数组以与另一个数组匹配

时间:2018-08-10 20:22:54

标签: javascript arrays

我有一个数组数组,我想用另一个数组的值迭代该数组以寻找匹配项。

'(search-text:patient*) OR (search-text:adult*)'

如果arr1 [i]中的所有值都存在于arr2中,则我需要它返回真实的假值

let arr1 = [[1,3,5],[2,4,7],[1,5,9]] // [false, false, true]
let arr2 = [1,2,4,5,9] // arr2 contains all values of arr1[2]. return true.

2 个答案:

答案 0 :(得分:2)

您可以将.map().every()一起使用

let arr1 = [[1,3,5],[2,4,7],[1,5,9]];
let arr2 = [1,2,4,5,9];
let result = arr1.map(x => x.every(y => arr2.includes(y)));
console.log(result);

.filter(),如果您只想获得匹配的结果:

let arr1 = [[1,3,5],[2,4,7],[1,5,9]];
let arr2 = [1,2,4,5,9];
let result = arr1.filter(x => x.every(y => arr2.includes(y)));
console.log(result);

答案 1 :(得分:1)

您可以通过对每个内部数组使用Array#some来为单个布尔值使用Array#every,并用Array#includes来检查array2

var array1 = [[1, 3, 5], [2, 4, 7], [1, 5, 9]],
    array2 = [1, 2, 4, 5, 9],
    result = array1.some(a => a.every(v => array2.includes(v)));
    
console.log(result);

使用Set

var array1 = [[1, 3, 5], [2, 4, 7], [1, 5, 9]],
    array2 = [1, 2, 4, 5, 9],
    result = array1.some((s => a => a.every(v => s.has(v)))(new Set(array2)));
    
console.log(result);