gpt4 book ai didi

javascript - 从数组中删除具有特征 X 的所有元素,最新的除外

转载 作者:搜寻专家 更新时间:2023-11-01 00:27:13 24 4
gpt4 key购买 nike

我有以下对象:

[
{ name: "Peter", id: 25, job: "carpenter" },
{ name: "Peter", id: 25, job: "shelf maker" },
{ name: "John", no: 20, job: "student" },
{ name: "John", id: 20, job: "university student" },
{ name: "John", id: 20, job: "student at uni still" },
{ name: "Jack", id: 20, job: "university student" }
]

我想遍历这个数组,每当 nameid 相同时,我只想保留一个条目,即 最新出现的那个 在数组中,并丢弃所有其余部分。我该怎么做?

我试过了

for(let i=0;i<people.length;i++) {
const person = people[i];
const result = people.filter(person => person.id === id && person.name === name);

people[i] = person;
}

...但这不起作用。任何想法我做错了什么?你会如何处理这个问题?

最佳答案

您可以使用 reduceRight 构建新数组,从数组末尾开始迭代,也可以使用 Map 作为累加器值来存储 key - value 对。

const data = [{"name":"Peter","id":25,"job":"carpenter"},{"name":"Peter","id":25,"job":"shelf maker"},{"name":"John","no":20,"job":"student"},{"name":"John","id":20,"job":"university student"},{"name":"John","id":20,"job":"student at uni still"},{"name":"Jack","id":20,"job":"university student"}]

const map = data.reduceRight((r, e) => {
const key = `${e.name}|${e.id}`;
if (!r.has(key)) r.set(key, e);
return r;
}, new Map);

const uniq = [...map.values()];
console.log(uniq)

关于javascript - 从数组中删除具有特征 X 的所有元素,最新的除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com