我有一个重复的数组:
nameList = [{name:"name1", filename:"filename1"}, {name:"name2", filename:"filename2"}, {name:"name3", filename:"filename2"}]
,我只想保留唯一项,而只保留最后一项。我想要:
nameList = [{name:"name1", filename:"filename1"}, {name:"name3", filename:"filename2"}]
我尝试过:
var flags = {};
resultNameList = nameList.filter(function(entry) {
if (flags[entry.filename]) {
return false;
}
flags[entry.filename] = true;
return true;
});
,但仅保留第一次出现的重复项。如何获得最后一次出现?
请帮助。谢谢。
答案 0 :(得分:2)
减少由filename
属性索引的对象,如果存在则覆盖累加器中该键上的上一个项目-这样可确保在所有迭代之后,该对象的值仅由给定的最新出现组成文件名。然后取累加器的值:
const nameList = [{
name: "name1",
filename: "filename1"
}, {
name: "name2",
filename: "filename2"
}, {
name: "name3",
filename: "filename2"
}];
const output = Object.values(nameList.reduce((a, item ) => {
a[item.filename] = item;
return a;
}, {}));
console.log(output);
请注意,对象中的键值对必须用:
而不是=
分隔。
以下注释中给出的输入看起来也可以按需工作:
const nameList = [{
name: "name1",
filename: "filename1"
}, {
name: "name3",
filename: "filename2"
}];
const output = Object.values(nameList.reduce((a, item) => {
a[item.filename] = item;
return a;
}, {}));
console.log(output);