javascript - 用下划线分组和求和

标签 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

数据集很大,所以性能很重要。

最佳答案

可以使用一个相当简单的 native 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>

关于javascript - 用下划线分组和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48178242/

相关文章:

javascript - 如何在 JS 中将对象转换为数组列表

javascript - 为什么 _.delay 将我的 e.type 从 mouseenter 变为 mouseover

javascript - 无法在刚刚插入的 HTML 中找到 jQuery 类的元素

javascript - 将 json 的每个对象的值集推送到不同的数组中

javascript - 显示符合特定条件的帖子总数

javascript - 响应式移动菜单的 jQuery 问题

javascript - 如何在 DIV 元素上合成浏览器点击事件?

元素循环中的 javascript onclick 事件 [无 jQuery]

javascript - 原型(prototype)javascript混淆

javascript - 下划线 _.object 但具有重复的处理函数,可能吗?