You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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']

代码说明

  1. 以单词数组arr2作为过滤主体,逐一遍历每个待校验的单词
  2. 调用arr1.every()遍历所有句子,仅当所有句子都不包含当前单词时,校验才通过,该单词会被保留到结果数组中
  3. 如果需要不区分大小写匹配,可以调整判断逻辑为:
    arr1.every(sentence => !sentence.toLowerCase().includes(word.toLowerCase()))

内容的提问来源于stack exchange,提问作者zaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:48:03