2 回答
TA贡献1878条经验 获得超4个赞
您可以通过Array.prototype.every在needle数组上使用来做到这一点:
let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];
function checkArraySubset(innerArray, outerArray){
return innerArray.every(str => outerArray.includes(str));
}
//true
console.log(checkArraySubset(needle, haystack));
needle = ['iridology','health tips', 'not present in haystack'];
//false
console.log(checkArraySubset(needle, haystack));
haystack如果数组太长,则从数组中创建一个集合,这将导致 O(1) 查找:
let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];
function checkArraySubset(innerArray, outerArray){
const lookup = new Set(outerArray);
return innerArray.every(str => lookup.has(str));
}
//true
console.log(checkArraySubset(needle, haystack));
TA贡献1785条经验 获得超4个赞
使用reduce和的一种可能方式includes
let haystack = ['health tips','iridology','something else','asdfasd'];
let needle = ['iridology','health tips'];
const found = needle.reduce((acc, item) => acc && haystack.includes(item), true);
console.log('found ', found);
添加回答
举报