Group by multiple fields Underscore.JS

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;

Find the underscore groupBy Tutorial output


Google Matched Content...