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

如何在JavaScript对象数组中保留number字段重复项并移除唯一值

过滤保留number字段重复的对象数组

方法一:先统计次数再过滤

先遍历数组统计每个number的出现次数,再过滤出次数≥2的对象:

const array = [
  { number: 1, color: "red" },
  { number: 2, color: "blue" },
  { number: 2, color: "yellow" },
  { number: 3, color: "black" },
  { number: 3, color: "orange" },
  { number: 4, color : "white" }
];

// 统计每个number的出现次数
const countMap = {};
array.forEach(item => {
  countMap[item.number] = (countMap[item.number] || 0) + 1;
});

// 过滤出number出现次数≥2的对象
const result = array.filter(item => countMap[item.number] >= 2);
console.log(result);

方法二:利用连续重复特性优化(更高效)

已知重复对象始终连续,我们可以只遍历一次数组,按组处理重复项:

const array = [
  { number: 1, color: "red" },
  { number: 2, color: "blue" },
  { number: 2, color: "yellow" },
  { number: 3, color: "black" },
  { number: 3, color: "orange" },
  { number: 4, color : "white" }
];

const result = [];
let currentNumber = null;
let currentGroup = [];

for (const item of array) {
  if (item.number === currentNumber) {
    currentGroup.push(item);
  } else {
    // 切换number时,检查上一组是否有重复项,有则加入结果
    if (currentGroup.length >= 2) {
      result.push(...currentGroup);
    }
    currentNumber = item.number;
    currentGroup = [item];
  }
}

// 处理最后一组数据
if (currentGroup.length >= 2) {
  result.push(...currentGroup);
}

console.log(result);

输出结果

两种方法都会得到你需要的结果:

[
  { number: 2, color: "blue" },
  { number: 2, color: "yellow" },
  { number: 3, color: "black" },
  { number: 3, color: "orange" }
]

方法一逻辑直观,适合普通场景;方法二利用重复项连续的特性,无需额外存储全量次数统计,内存占用更低,适合处理大型数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 21:35:00