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

如何在两个对象数组中按ID取交集并返回最低score实例?

解决方案

要实现按ID取交集并保留每个ID对应score最低的对象,可以通过构建ID映射提升效率(避免嵌套循环的O(n*m)复杂度),再合并筛选出最小score项:

单函数实现

const getMinScoreIntersection = (arr1, arr2) => {
  // 将第二个数组转为ID为键的Map,实现O(1)快速查找
  const idMap = new Map(arr2.map(item => [item.id, item]));
  
  // 遍历第一个数组,完成交集判断、score比较与结果收集
  return arr1.reduce((result, item) => {
    const match = idMap.get(item.id);
    if (match) {
      // 取当前项与匹配项中score更小的对象
      const minItem = item.score <= match.score ? item : match;
      // 避免重复添加同ID项(兼容原数组存在重复ID的场景)
      const existingIndex = result.findIndex(i => i.id === item.id);
      if (existingIndex === -1) {
        result.push(minItem);
      } else if (minItem.score < result[existingIndex].score) {
        result[existingIndex] = minItem;
      }
    }
    return result;
  }, []);
};

示例验证

用你提供的测试数据验证:

const array1 = [
  {id:'aaa',score:5},
  {id:'bbb',score:5},
  {id:'ccc',score:20},
  {id:'xxx',score:1},
  {id:'yyy',score:1},
  {id:'zzz',score:20},
];
const array2 = [
  {id:'aaa',score:1},
  {id:'bbb',score:1},
  {id:'ccc',score:5},
  {id:'zzz',score:60},
];

const shared = getMinScoreIntersection(array1, array2);
console.log(shared);
// 输出结果与预期一致:
// [
//   {id:'aaa',score:1},
//   {id:'bbb',score:1},
//   {id:'ccc',score:5},
//   {id:'zzz',score:20}
// ]

排序处理

如果需要按score升序、id升序排序,直接对结果调用sort即可:

shared.sort((a, b) => {
  if (a.score !== b.score) return a.score - b.score;
  return a.id.localeCompare(b.id);
});

简化版(适用于ID唯一场景)

若确定两个数组中每个ID仅出现一次,可省略去重逻辑进一步简化:

const getMinScoreIntersection = (arr1, arr2) => {
  const idMap = new Map(arr2.map(item => [item.id, item]));
  return arr1.reduce((res, item) => {
    const match = idMap.get(item.id);
    if (match) res.push(item.score <= match.score ? item : match);
    return res;
  }, []);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:00:48