Lodash group by multiple properties if property value is true

前端 未结 8 1930
执笔经年
执笔经年 2020-12-10 02:20

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

8条回答
  •  心在旅途
    2020-12-10 02:52

    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'));

提交回复
热议问题