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.

4

1 回答 1

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

于 2013-03-30T12:16:35.580 回答