What the best way to remove duplicates from an array of objects?
var array = [
{a: 0, b: 0, c: 0},
{a: 0, b: 0, c: 0},
{a: 1, b: 1, c: 1},
{a: 1, b: 1, c: 1},
//..... etc
];
And, i want to get like:
[
{a: 0, b: 0, c: 0},
{a: 1, b: 1, c: 1}
];
PS: the keys (a, b, c) have only primitive data type (String, Number)
Please, without underscore.js and other libs.
1 Answer 1
I'm sure there is better ways to do this, but you can use this prototype function.
Array.prototype.removeDuplicates = function () {
var r = new Array();
o:for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
if(r[x].a==this[i].a && r[x].b==this[i].b && r[x].c==this[i].c)
continue o;
r.push(this[i]);
}
return r;
}
How to use it
var arr = [
{a: 0, b: 0, c: 0},
{a: 0, b: 0, c: 0},
{a: 1, b: 1, c: 1},
{a: 1, b: 1, c: 1},
//..... etc
];
var uniques = arr.removeDuplicates();
console.log(uniques);
Note:
You should avoid this for big arrays, out there are better solutions
answered Jan 31, 2013 at 21:04
Tomas Ramirez Sarduy
17.5k8 gold badges74 silver badges86 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Robbin
Could you rewrite your example without o: ?
Tomas Ramirez Sarduy
@Robbin: I think a better idea is that you rewrite the code. Hint: use a bit (value 0 or 1) inside loop
Lion789
How big of arrays should be avoided, and I have been looking, anyone have a link or can state a better solution, I have the same issue but have arrays with a couple thousand objects to go through...
Tomas Ramirez Sarduy
@Lion789: In that case you need to study algorithms for that and maybe some heuristics
Lion789
Ok, by the way, using the above prototype, how would you go about removing duplicates and merging two or more arrays?
lang-js
cs?