列表是
{id: 11, type: "sell", quantity: 11, price: 155}
{id: 11, type: "sell", quantity: 11, price: 155}
{id: 11, type: "sell", quantity: 11, price: 155}
{id: 12, type: "buy", quantity: 3, price: 189}
{id: 13, type: "buy", quantity: 4, price: 189}
{id: 14, type: "buy", quantity: 2, price: 189}
{id: 14, type: "buy", quantity: 2, price: 189}
(近1000个项目) 我想从javascript中的列表中删除重复项,例如,ID为11和14的项具有重复项,因此新列表将在删除后
{id: 12, type: "buy", quantity: 3, price: 189}
{id: 13, type: "buy", quantity: 4, price: 189}
重复项将在新数组中被完全删除,而不是它仍然会在新数组中存在
答案 0 :(得分:1)
您可以使用Set
作为已访问过的id
的闭包,并从结果集中删除该对象(如果存在)。
此方法对数据使用单个循环,对每个发现的重复项都进行过滤。
var array = [{ id: 11, type: "sell", quantity: 11, price: 155 }, { id: 11, type: "sell", quantity: 11, price: 155 }, { id: 11, type: "sell", quantity: 11, price: 155 }, { id: 12, type: "buy", quantity: 3, price: 189 }, { id: 13, type: "buy", quantity: 4, price: 189 }, { id: 14, type: "buy", quantity: 2, price: 189 }, { id: 14, type: "buy", quantity: 2, price: 189 }],
single = array.reduce((s => (r, o) => {
if (s.has(o.id)) {
return r.filter(({ id }) => id !== o.id);
}
s.add(o.id);
r.push(o);
return r;
})(new Set), []);
console.log(single);
.as-console-wrapper { max-height: 100% !important; top: 0; }