Underscore.js, remove duplicates in array of objects based on key value

∥☆過路亽.° 提交于 2019-12-23 09:33:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!