删除对象数组中的重复项 Javascript [英] Remove duplicates in an object array 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
甚至 _.contains
但找不到令人满意的解决方案.
I've tried _.uniq
or even _.contains
but couldn't find a satisfying solution.
谢谢!
该问题已被识别为与另一个问题重复.我在发布之前看到了这个问题,但它没有回答我的问题,因为它是一个对象数组(而不是一个二维数组,谢谢 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:
const list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}];
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;
}
console.log(dedupe(list));
这篇关于删除对象数组中的重复项 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!