【发布时间】:2023-03-09 07:50:01
【问题描述】:
我发现以下answer 对删除包含重复项的重复对象数组有很大帮助。
我已经为我修改的示例制作了fork。
相关功能:
const uniqueArray = things.thing.filter((thing,index) => {
return index === things.thing.findIndex(obj => {
return JSON.stringify(obj) === JSON.stringify(thing);
});
});
例如我有:
[
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"},
{"place":"there","name":"morestuff"},
{"place":"herehere","name":"stuff"}
]
它会返回:
[
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"},
{"place":"herehere","name":"stuff"}
]
如何删除包含相同name 的重复place 名称?
预期输出:
[
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"}
]
【问题讨论】:
-
您可能希望使用 Array.reduce 代替,其中累加器是“过滤”对象,只有当累加器不包含所需项目时才会推送下一个项目。
const uniqueArray = things.thing.reduce((acc, next) => { if (acc.find(i => i.place === next.place)) return acc; else return (acc.push(next), acc); }, []); -
对不起,我忘了放预期的输出。
标签: javascript arrays object duplicates