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

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 exclude indexes with duplicate names and recreate a new array with different names, for example:

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 deleted “Bob” and “Tom”, leaving only 3 different names. Is this possible with Underscore? How?

+2
source share
2 answers

Use _.uniqwith a custom conversion, such as _.property('name')you would do nicely or simply 'name', as @Gruff Bunny noted in the comments:

var mySubArray = _.uniq(myArray, 'name');

And the demo http://jsfiddle.net/nikoshr/02ugrbzr/

+16

, , , , , , :

var mySubArray = []

_.each(_.uniq(_.pluck(myArray, 'name')), function(name) {
    mySubArray.push(_.findWhere(myArray, {name: name}));
})
+2

Source: https://habr.com/ru/post/1665384/


All Articles