3

I am trying to use the underscore unique function, but could not get it to work, here is my test code:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

_.unique(foo,  function(item, k, v){
    return item.a;
});
console.log(foo);

_.unique(foo, 'a');
console.log(foo);

As refered here: Removing duplicate objects with Underscore for Javascript, and the test code is here: http://jsfiddle.net/bingjie2680/wDvpM/2/, both prints out three objects. I could not figure out the problem, can anybody help? thanks a lot.

Community
  • 1
  • 1
bingjie2680
  • 7,643
  • 8
  • 45
  • 72

1 Answers1

6

uniq returns a new array. And the function doesn't seem to like it when you omit the second argument.

This works :

var foo2 = _.unique(foo, false, function(item, k, v){
    return item.a;
});

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758