删除对象数组Javascript中的重复项 [英] Remove duplicates in an object array Javascript
本文介绍了删除对象数组Javascript中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组
list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}]
我正在寻找一种有效的方法(如果可能的话 O(log(n))
)来删除重复项并最终结束
And I'm looking for an efficient way (if possible O(log(n))
) to remove duplicates and to end up with
list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}]
我试过 _。uniq
甚至 _。包含
但找不到令人满意的解决方案。
I've tried _.uniq
or even _.contains
but couldn't find a satisfying solution.
谢谢!
编辑:该问题已被确定为另一个问题的副本。我在帖子之前看到了这个问题,但它没有回答我的问题,因为它是一个对象数组(而不是一个2-dim数组,感谢Aaron),或者至少其他问题的解决方案在我的情况下不起作用。
Edit : The question has been identified as a duplicate of another one. I saw this question before posting but it didn't answer my question since it's an array of object (and not a 2-dim array, thanks Aaron), or at least the solutions on the other question weren't working in my case.
推荐答案
Vanilla JS版本:
Vanilla JS version:
function dedupe(arr) {
return arr.reduce(function (p, c) {
// create an identifying id from the object values
var id = [c.x, c.y].join('|');
// if the id is not found in the temp array
// add the object to the output array
// and add the key to the temp array
if (p.temp.indexOf(id) === -1) {
p.out.push(c);
p.temp.push(id);
}
return p;
// return the deduped array
}, { temp: [], out: [] }).out;
}
dedupe(list);
这篇关于删除对象数组Javascript中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文