0

Input:

var animals = [
    {category: "mammal", name: "dog", categoryID: "MAM"},
    {category: "fish", name: "pickerel", categoryID: "FIS"},
    {category: "mammal", name: "cat", categoryID: "MAM"},
    {category: "mammal", name: "monkey", categoryID: "MAM"},
    {category: "bird", name: "budgie", categoryID: "BIRD"}
];

Desired output:

var categories = [
 {name: "mammal", catId: "MAM"},
 {name: "bird", catId: "BIR"},
 {name: "fish", catId: "FIS"}
];

Is there a nice way to do it with underscore?

The closest I got was this jsFiddle:

var categories = _.groupBy(animals, function(animal) {
                    return animal.category;
                });

With this output:

Object {mammal: Array[3], fish: Array[1], bird: Array[1]}

But is there a way to return the desired output above in a nice way?

1 Answer 1

1

You can use reduce instead of groupBy to collect your names and IDs in a convenient format:

var collect_categories = function(o, e) {
    o[e.categoryID] = e.category;
    return o;
};
var o = _(animals).reduce(collect_categories, { })

and then a map to unpack that object into an array of objects:

var unpack = function(name, id) {
    return { name: name, catID: id };
};
var a = _(o).map(unpack);

The helper functions make more sense when you combine those with chain:

var categories = _(animals).chain()
                           .reduce(collect_categories, { })
                           .map(unpack)
                           .value();

I find that naming the functions makes the code less cluttered than anonymous functions and the names help to signal the code's intent.

Demo: http://jsfiddle.net/ambiguous/aS47C/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.