1

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.

12
  • 1
    What happened to the cs? Commented Jan 31, 2013 at 19:41
  • 1
    Also, does order matter? Commented Jan 31, 2013 at 19:41
  • 1
    Finally... why not use underscore? Commented Jan 31, 2013 at 19:42
  • 1
    What is your equality function? I.e. what does it mean for two objects to be duplicative of one another? Are you assuming no-one will mutate elements of this array? Commented Jan 31, 2013 at 19:42
  • 2
    @Dancrumb, I dont want to use the underscore.js in my project, because there're no any reasons for it Commented Jan 31, 2013 at 22:50

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Could you rewrite your example without o: ?
@Robbin: I think a better idea is that you rewrite the code. Hint: use a bit (value 0 or 1) inside loop
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...
@Lion789: In that case you need to study algorithms for that and maybe some heuristics
Ok, by the way, using the above prototype, how would you go about removing duplicates and merging two or more arrays?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.