How can an array be grouped by two properties?

后端 未结 3 1894
感情败类
感情败类 2021-01-20 20:25

Ex:

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,         


        
3条回答
  •  再見小時候
    2021-01-20 21:25

    @Bergi's answer is great if you can hard-code the inputs.

    If you want to use string inputs instead, you can use the sort() method, and walk the objects as needed.

    This solution will handle any number of arguments:

    function groupBy(arr) {
      var arg = arguments;
      
      return arr.sort((a, b) => {
        var i, key, aval, bval;
        
        for(i = 1 ; i < arguments.length ; i++) {
          key = arguments[i].split('.');
          aval = a[key[0]];
          bval = b[key[0]];
          key.shift();
          while(key.length) {  //walk the objects
            aval = aval[key[0]];
            bval = bval[key[0]];
            key.shift();
          };
          if     (aval < bval) return -1;
          else if(aval > bval) return  1;
        }
        return 0;
      });
    }
    
    const arr = [{
      group: 1,
      question: {
        templateId: 100
      }
    }, {
      group: 2,
      question: {
        templateId: 200
      }
    }, {
      group: 1,
      question: {
        templateId: 100
      }
    }, {
      group: 1,
      question: {
        templateId: 300
      }
    }];
    
    const result = groupBy(arr, 'group', 'question.templateId');
    
    console.log(result);

提交回复
热议问题