12

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?

2
  • 2
    I'm pretty sure this use case demands more than just _.filter Commented Mar 11, 2015 at 15:42
  • @GeorgeJempty: I tried _.filter but maybe I couldn't find a way to use it properly. Commented Mar 11, 2015 at 15:49

2 Answers 2

36

With Underscore, 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/

If you use Lodash and not Underscore, go with the example given by @Jacob van Lingen in the comments and use _.uniqBy:

var mySubArray = _.uniqBy(myArray, 'name')
Sign up to request clarification or add additional context in comments.

3 Comments

You could just pass 'name' as the third parameter to _.uniq
and remove the second parameter leaving just _.uniq(myArray, 'name') - just peeked at the underscore source
Note for lodash, it is: _.uniqBy(myArray, 'name')
3

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}));
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.