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

JavaScript:如何从重复对象数组中获取每个对象的最后实例?

获取数组中重复对象的最后一个实例解决方案

需求:从包含重复对象的数组中,提取每个name对应的最后一个对象实例。

输入示例

[
  {name:'Sam', count:3},
  {name:'Sam', count:5},
  {name:'Sam', count:8},
  {name:'Jill', count:7},
  {name:'Jill', count:6},
]

期望输出示例

[
  {name:'Sam', count:8},
  {name:'Jill', count:6},
]

解决方案

方法一:使用Array.prototype.reduce()

利用reduce遍历数组,以对象作为累加器,用name作为唯一键,每次遍历都覆盖同键对应的对象,最终将累加器的取值转为数组即可得到结果。

const input = [
  {name:'Sam', count:3},
  {name:'Sam', count:5},
  {name:'Sam', count:8},
  {name:'Jill', count:7},
  {name:'Jill', count:6},
];

const result = Object.values(input.reduce((acc, curr) => {
  acc[curr.name] = curr;
  return acc;
}, {}));

console.log(result);

方法二:使用Map

Map的键具有唯一性,遍历数组时用name作为键存入Map,后续同键的对象会覆盖之前的,最后通过Array.from()将Map的值转为数组。

const input = [
  {name:'Sam', count:3},
  {name:'Sam', count:5},
  {name:'Sam', count:8},
  {name:'Jill', count:7},
  {name:'Jill', count:6},
];

const map = new Map();
input.forEach(item => map.set(item.name, item));
const result = Array.from(map.values());

console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:25:20