问题
I have the following JS array:
var myArray = [{name:"Bob",b:"text2",c:true},
{name:"Tom",b:"text2",c:true},
{name:"Adam",b:"text2",c:true},
{name:"Tom",b:"text2",c:true},
{name:"Bob",b:"text2",c:true}
];
I want to eliminate the indexes with name value duplicates and recreate a new array, with distinct names, eg:
var mySubArray = [{name:"Bob",b:"text2",c:true},
{name:"Tom",b:"text2",c:true},
{name:"Adam",b:"text2",c:true},
];
As you can see, I removed "Bob" and "Tom", leaving only 3 distinct names. Is this possible with Underscore? How?
回答1:
Use _.uniq with a custom transformation, a function like _.property('name') would do nicely or just 'name'
, as @Gruff Bunny noted in the comments :
var mySubArray = _.uniq(myArray, 'name');
And a demo http://jsfiddle.net/nikoshr/02ugrbzr/
回答2:
The other answer is definitely best but here's another that's not much longer that also exposes you to more underscore method's, if you're interested in learning:
var mySubArray = []
_.each(_.uniq(_.pluck(myArray, 'name')), function(name) {
mySubArray.push(_.findWhere(myArray, {name: name}));
})
来源:https://stackoverflow.com/questions/28991014/underscore-js-remove-duplicates-in-array-of-objects-based-on-key-value