Reputation: 6381
Given I have an array like this
var arr = [ { "language" : "en", "level" : "C2", "primary" : true },
{ "language" : "fr", "level" : "B1", "learning" : true },
{ "language" : "it", "level" : "A2" } ]
I want to collect all the "language" values into a single array, like this:
["en", "fr", "it"]
I know I can do it with a for loop, but how would I do it with Underscore / LoDash?
How would I order by one of the boolean fields, and then alpha ie: if ordering by the "learning" boolean:
["fr", "en", "it"]
Upvotes: 0
Views: 43
Reputation: 2963
Use the combination of _.sortByAll
and _.pluck
functions (link to jsbin):
var arr = [ { "language" : "en", "level" : "C2", "primary" : true },
{ "language" : "fr", "level" : "B1", "learning" : true },
{ "language" : "it", "level" : "A2" } ];
var res = _.pluck(_.sortByAll(arr, 'learning', 'language'), 'language');
console.log(res);
.sortByAll will sort your array firt by learning
field and then by language
. And .pluck will take the given field from every object in the array (language
in your case).
Upvotes: 2