Lodas map and unique feedback

I have a lodash variable;

var usernames = _.map(data, 'usernames'); 

which produces the following:

 [ "joebloggs", "joebloggs", "simongarfunkel", "chrispine", "billgates", "billgates" ] 

How can I configure the lodash operator to return only an array of unique values? eg.

 var username = _.map(data, 'usernames').uniq(); 
+15
source share
2 answers

Many ways, but uniq() not a method in an array, it is a lodash method.

 _.uniq(_.map(data, 'usernames')) 

Or:

 _.chain(data).map('usernames').uniq().value() 

(The second is untested and possibly incorrect, but it closes.)

As mentioned in the commentary, depending on your data, in fact, you can do this with just one shot without pulling all usernames out of it.

+45
source

You can also use the uniqBy function uniqBy which also accepts iteratee, called for each element in the array. It takes two arguments, as shown below, where id is the iteratee parameter.

 _.uniqBy(array, 'id') 
0
source

All Articles