I have an array of vehicles that need to be grouped by make and model, only if the \'selected\' property is true. The resulting object should contain properties for make mod
const multiGroupBy = (array, group, ...restGroups) => {
if(!group) {
return array;
}
const currGrouping = _.groupBy(array, group);
if(!restGroups.length) {
return currGrouping;
}
return _.transform(currGrouping, (result, value, key) => {
result[key] = multiGroupBy(value, ...restGroups);
}, {});
};
console.log(multiGroupBy([{x:1,y:1,z:1},{x:1,y:2,z:1},{x:2,y:1,z:1},{x:2,y:2,z:1},{x:1,y:1,z:2},{x:1,y:2,z:2},{x:2,y:1,z:2},{x:2,y:2,z:2}],'x','y'));
or if you prefer old syntax
function multiGroupBy(array, group) {
if(!group) {
return array;
}
var currGrouping = _.groupBy(array, group);
var restGroups = Array.prototype.slice.call(arguments);
restGroups.splice(0,2);
if(!restGroups.length) {
return currGrouping;
}
return _.transform(currGrouping, function(result, value, key) {
result[key] = multiGroupBy.apply(null, [value].concat(restGroups));
}, {});
}
console.log(multiGroupBy([{x:1,y:1,z:1},{x:1,y:2,z:1},{x:2,y:1,z:1},{x:2,y:2,z:1},{x:1,y:1,z:2},{x:1,y:2,z:2},{x:2,y:1,z:2},{x:2,y:2,z:2}],'x','y'));