我一直在努力删除数组中的重复对象。我在尝试读取filterList [i + 1] .tagID时遇到错误。我可以手动输入[i + 1]值并获得正确的结果。我不确定为什么i + 1是一个问题。我还想知道是否使用切片[i,1]比删除更好。
pandas

答案 0 :(得分:3)
您可以使用set
对象删除重复的ID,然后使用map
和find
函数来改变结果,只为每个tagID
提供第一个外观
Array.from(new Set(filterList.map(_=> _.tagID)))
.map(ID=> filterList.find(o=> o.tagID === ID)));
const filterList = [{
tagID: 1,
tagName: "Red"
}, {
tagID: 1,
tagName: "Red"
}, {
tagID: 2,
tagName: "Orange"
}, {
tagID: 2,
tagName: "Orange"
}, {
tagID: 5,
tagName: "Blue"
}, {
tagID: 5,
tagName: "Blue"
}, {
tagID: 5,
tagName: "Blue"
}, {
tagID: 6,
tagName: "Indigo"
}, {
tagID: 6,
tagName: "Indigo"
}, {
tagID: 7,
tagName: "Violet"
}, {
tagID: 7,
tagName: "Violet"
}, {
tagID: 7,
tagName: "Violet"
}]
let result = Array.from(new Set(filterList.map(_ => _.tagID))).map((ID, index) => filterList.find(o => o.tagID == ID));
console.log(result);
答案 1 :(得分:3)
试试这个!使用过滤器和es2015
const filterListResult = filterList.filter((item, index, self) => index === self.findIndex((t) => (t.tagID === item.tagID && t.tagName === item.tagName)));
console.log(filterListResult);
<script>
const filterList = [{
tagID: 1,
tagName: "Red"
}, {
tagID: 1,
tagName: "Red"
}, {
tagID: 2,
tagName: "Orange"
}, {
tagID: 2,
tagName: "Orange"
}, {
tagID: 5,
tagName: "Blue"
}, {
tagID: 5,
tagName: "Blue"
}, {
tagID: 5,
tagName: "Blue"
}, {
tagID: 6,
tagName: "Indigo"
}, {
tagID: 6,
tagName: "Indigo"
}, {
tagID: 7,
tagName: "Violet"
}, {
tagID: 7,
tagName: "Violet"
}, {
tagID: 7,
tagName: "Violet"
}]
</script>
答案 2 :(得分:2)
您可以从索引1
开始迭代,并使用实际元素检查最后一个元素。
const filterList = [{ tagID: 1, tagName: "Red" }, { tagID: 1, tagName: "Red" }, { tagID: 2, tagName: "Orange" }, { tagID: 2, tagName: "Orange" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 6, tagName: "Indigo" }, { tagID: 6, tagName: "Indigo" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }]
filterList.sort(function(a, b) {
return a.tagID - b.tagID;
});
for (let i = 1; i < filterList.length; i++) {
if (filterList[i - 1].tagId === filterList[i].tagID) {
delete filterList[i];
}
}
console.log(filterList);
&#13;
答案 3 :(得分:2)
使用reduce:
生成新列表const filterList = [{ tagID: 1, tagName: "Red" }, { tagID: 1, tagName: "Red" }, { tagID: 2, tagName: "Orange" }, { tagID: 2, tagName: "Orange" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 6, tagName: "Indigo" }, { tagID: 6, tagName: "Indigo" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }]
const newList = filterList.reduce((total, current) => {
const exist = total.some(t => t.tagID === current.tagID)
if (!exist) {
total.push(current)
}
return total
}, [])