JavaScript中如何对比两个数组并过滤存在部分匹配的元素
实现方案
核心逻辑
- 遍历待过滤的单词数组,对每个单词检查是否在所有句子中都不存在,符合条件的保留
完整代码
const arr1 = ['hello from the other side', 'very nice boy,john']; const arr2 = ['nice', 'work']; // 过滤单词数组,仅保留未出现在任何句子中的单词 const filteredWords = arr2.filter(word => arr1.every(sentence => !sentence.includes(word))); console.log(filteredWords); // 输出:['work']
代码说明
- 以单词数组
arr2作为过滤主体,逐一遍历每个待校验的单词 - 调用
arr1.every()遍历所有句子,仅当所有句子都不包含当前单词时,校验才通过,该单词会被保留到结果数组中 - 如果需要不区分大小写匹配,可以调整判断逻辑为:
arr1.every(sentence => !sentence.toLowerCase().includes(word.toLowerCase()))
内容的提问来源于stack exchange,提问作者zaid
相关产品推荐
相关产品推荐

