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

如何通过另一数组的值过滤对象数组,实现去重与前缀匹配?

解决方案:合并数组去重与前缀过滤

你可以把去重和黑名单前缀过滤的逻辑合并到一次filter遍历中,既简洁又高效。以下是具体实现:

完整代码示例

let blacklistedComponents = ["F11", "U30"];
let components = [
  { id: "F11v6", type: "unknown" },
  { id: "U30v3", type: "unknown" },
  { id: "CH11", type: "unknown" },
  { id: "CT12", type: "true" },
  { id: "U03v5", type: "unknown" },
  { id: "CT12", type: "true" }
];

// 同时完成去重和过滤的逻辑
const filteredResult = components.filter((v, i, arr) => {
  // 1. 去重:只保留每个id第一次出现的对象
  const isFirstId = arr.findIndex(item => item.id === v.id) === i;
  // 2. 过滤:排除id以黑名单中任意前缀开头的对象
  const isAllowed = !blacklistedComponents.some(prefix => v.id.startsWith(prefix));
  // 两个条件都满足才保留
  return isFirstId && isAllowed;
});

console.log(filteredResult);

代码解释

  • 去重逻辑:arr.findIndex(item => item.id === v.id) === i 会检查当前对象的id是否是第一次出现,只有第一次出现的对象才会被保留。
  • 过滤逻辑:blacklistedComponents.some(prefix => v.id.startsWith(prefix)) 会判断当前对象的id是否以黑名单中的任意字符串开头,取反后就得到“允许保留”的条件。

输出结果会自动移除F11v6、U30v3以及重复的CT12,最终保留:

[
  { id: "CH11", type: "unknown" },
  { id: "CT12", type: "true" },
  { id: "U03v5", type: "unknown" }
]

高效优化版(适合大数据量)

如果你的数组很大,上面的去重逻辑因为findIndex会导致O(n²)的时间复杂度,可以用Set来记录已出现的id,把时间复杂度降到O(n):

const seenIds = new Set();
const filteredResult = components.filter(v => {
  const isAllowed = !blacklistedComponents.some(prefix => v.id.startsWith(prefix));
  if (isAllowed && !seenIds.has(v.id)) {
    seenIds.add(v.id);
    return true;
  }
  return false;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:40:19