20

I've looked at this Stack question, "Removing duplicate objects with Underscore for Javascript" and that is exactly what I am trying to do, but none of the examples work. In fact I can not get any iterator function to work with _.uniq.

_.uniq([1, 2, 1, 3, 1, 4]);
> [1, 2, 3, 4]
_.uniq([1, 2, 1, 3, 1, 4], false, function(a){ return a===4;});
> [1, 2, 3, 4]
_.uniq([1, 2, 1, 3, 1, 4], true, function(a){ return a===4;});
> [1, 2, 1, 3, 1, 4]
_.uniq([1, 2, 1, 3, 1, 4], false, function(a){ return false;});
> [1, 2, 3, 4]
_.uniq([1, 2, 1, 3, 1, 4], false, function(a){ return true;});
> [1, 2, 3, 4]

var people = [ { name: 'John', age: 20 }, { name: 'Mary', age: 31 }, { name: 'Kevin', age: 20 }]; 
_.uniq(people, false, function(p){ return p.age; });

> [ { age: 20, name: "John" }, 
    { age: 31, name: "Mary" },
    { age: 20, name: "Kevin" } ]

I would do:

_.uniq(_.map(people, function(p){ return p.age; }));
> [20, 31]

but it returns only the mapped value, not the original object.

Any help appreciated. I am using underscore version 1.1.7

Community
  • 1
  • 1
BishopZ
  • 6,269
  • 8
  • 45
  • 58
  • 2
    The examples you've shown work just fine for me (when I try them in console at Underscore's page) - and at [this fiddle](http://jsfiddle.net/bFgcY/) as well. BTW, 1.1.7 is pretty old; isn't that the reason? – raina77ow Oct 23 '12 at 16:40

2 Answers2

23

I had the same problem. It is caused because _.uniq() returns a new reduced array so you have to assing it to a variable. So with this little correction it has to work.

var people = [ { name: 'John', age: 20 }, { name: 'Mary', age: 31 }, { name: 'Kevin', age: 20 }];

people = _.uniq(people, false, function(p){ return p.age; });

[ { age: 20, name: "John" }, { age: 31, name: "Mary" } ]

user3851962
  • 231
  • 2
  • 2
15

Looks like comparison functions for _.uniq were introduced in 1.2.0

from the changelog:

_.uniq can now be passed an optional iterator, to determine by what criteria an object should be considered unique.

benjaminbenben
  • 1,218
  • 8
  • 15