underscore js _.groupby multiple values

Using underscore.js group the objects using multiple values. By default underscore not support the multiple value groupBy. Here we have to do the trick to achive the functionality.

_.groupBy will group the values using object keys or metric to group the objects or arrays. Let’s write the code. Find the code and example below

Underscore.JS groupBy Multiple values

_.groupByMulti = function (obj, values, context) {
    if (!values.length)
        return obj;
    var byFirst = _.groupBy(obj, values[0], context),
        rest = values.slice(1);
    for (var prop in byFirst) {
        byFirst[prop] = _.groupByMulti(byFirst[prop], rest, context);
    }
    return byFirst;
};
W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *