分组并用下划线加总

时间:2018-01-09 23:39:04

标签: javascript underscore.js

输入:

const data = [
  {
    id: 'RS11',
    name: 'Road 1',
    quantity: {
      lengthVal: 50
    }
  },
  {
    id: 'RS11',
    name: 'Road 1',
    quantity: {
      lengthVal: 100
    }
  },
   {
    id: 'RS11',
    name: 'Road 2',
    quantity: {
      lengthVal: 20
    }
  }
]

应将除quantity以外的每个属性进行分组。应该总结quantity.lengthVal。还应添加count属性。

预期产出:

const expected = [
  {
    id: 'RS11',
    name: 'Road 1',
    count: 2,
    summarizedLength: 150
  },
   {
    id: 'RS11',
    name: 'Road 2',
    count: 1,
    summarizedLength: 20
  }
]

这是我试过的:

const groupAndSum = (arr) => {
  return _.chain(arr)
    .groupBy((obj) => {
       // Some reduce here?
       return _.values(_.without(obj), 'quantity').join('|')
    })
    .map((val) => {
       val[0].count = val.length;
       delete val[0].quantity;
       return val[0];
    })
    .value();
}

Jsbin:https://jsbin.com/totujopume/edit?html,js,console

数据集非常大,因此性能很重要。

1 个答案:

答案 0 :(得分:2)

可以使用一个相当简单的原生reduce()来做到这一点,只有一次遍历整个过程的数组



const res = Object.values(
  data.reduce((a, c) => {
    const key = c.id + '|' + c.name;
    const o = a[key] = a[key] || c;
    o.count            = (o.count || 0) +1;
    o.summarizedLength = (o.summarizedLength || 0) + c.quantity.lengthVal;
    delete c.quantity;
    return a;
  },{})
);

console.log(res)

.as-console-wrapper {	max-height: 100%!important;}

<script>
  const data = [{
      id: 'RS11',
      name: 'Road 1',
      quantity: {
        lengthVal: 50
      }
    },
    {
      id: 'RS11',
      name: 'Road 1',
      quantity: {
        lengthVal: 100
      }
    },
    {
      id: 'RS11',
      name: 'Road 2',
      quantity: {
        lengthVal: 20
      }
    }
  ]
</script>
&#13;
&#13;
&#13;