如何基于嵌套数组键对对象数组去重并保留最后重复项
基于嵌套数组去重并保留最后出现的对象
给定如下对象数组:
const messages = [ { id: 1, name: "Jack", users: [2,4] }, { id: 2, name: "Alex", users: [2,6] }, { id: 3, name: "John", users: [2,6] } ]
需求是:依据对象中的users嵌套数组筛选唯一对象,若存在users数组内容重复的对象,仅保留最后出现的那条记录。预期结果为:
[{ id: 1, name: "Jack", users: [2,4] }, { id: 3, name: "John", users: [2,6] }]
解决方案
可以用Array.reduce()实现需求,核心是把users数组转成字符串作为唯一标识,遍历过程中让后续同标识的对象覆盖之前的,最后提取映射表的值即可。
代码示例
const messages = [ { id: 1, name: "Jack", users: [2,4] }, { id: 2, name: "Alex", users: [2,6] }, { id: 3, name: "John", users: [2,6] } ]; const uniqueMessages = Object.values( messages.reduce((acc, curr) => { // 将users数组转为字符串作为唯一键 const key = JSON.stringify(curr.users); // 后续对象覆盖同键的旧对象,自动保留最后一条 acc[key] = curr; return acc; }, {}) ); console.log(uniqueMessages);
思路说明
- 用
reduce遍历数组,初始化空对象作为累加器 - 对每个对象的
users数组做序列化,内容相同的数组会生成相同的字符串键 - 把当前对象赋值给累加器对应键,后续同键对象直接覆盖旧值,自然保留最后出现的记录
- 用
Object.values()把累加器里的对象转成数组,得到最终结果
内容的提问来源于stack exchange,提问作者Philemon Peter
相关产品推荐
相关产品推荐

