Lo-Dash array grouping

arrays, javascript, lodash

Solution

Here a more lo-dash, underscore way of doing it:

var result = _.reduce(characters, function (prev, current) {
    var char = _.find(prev, function (character) {
        return character['name'] === current['name'];
    });

    // Character does not yet exists in the array, push it
    if (char === undefined) {
        prev.push(current);
    } else {
        // If char['pet'] is not an array, create one
        if (!_.isArray(char['pet'])) {
            char['pet'] = [char['pet']];
        }

        // Push the current pets to the founded character
        char['pet'].push(current['pet']);
    }

    return prev;
}, []); // Initialize an empty array for the prev object

console.log(result);

Let me know if there is a more awesomeness feature in underscore/lodash :-)!

Fiddle

Problem

I spent hours on the Lo-Dash documentation site now, and can't find a solution for my problem. I don't know how it's called, so it is a bit hard to search for. I basically want to group an array into an object so that duplicate entries are a field while different entries are an array. For example, I have this array: ``` var characters = [ { 'name': 'barney', 'age': 42, 'pet': 'dog' }, { 'name': 'fred', 'age': 35, 'pet': 'dog' }, { 'name': 'barney', 'age': 42, 'pet': 'cat' }, { 'name': 'fred', 'age': 35, 'pet': 'goldfish' } ]; ``` And I want to get this: ``` [ { name: 'barney', age: 42, pet: [ 'dog', 'cat' ] }, { name: 'fred', age: 35, pet: [ 'dog', 'goldfish' ] } ] ``` Is there a Lo-Dash method for doing this, or do I have to chain several ones? What is the best way to achieve this?

Original source