首页 > 解决方案 > 数组分组和计数

问题描述

我正在尝试从以下数据示例中获取每日计数:

{ 'Tue Oct 01 2019': 3, 'Tue Oct 02 2019': 1 }

但我没有从下面的代码中得到预期的结果。

const data = [ { Date: 'Tue Oct 01 2019' },{ Date: 'Tue Oct 01 2019' },{ Date: 'Tue Oct 01 2019' }, { Date: 'Tue Oct 02 2019' } ];

const result = data.reduce((total, value) => {
  total[value] = (total[value] || 0) + 1;
  return total;
}, {});
console.log(result);

标签: javascript

解决方案


如果我对您的理解正确,您想要的是分组并获得计数:

const data = [ 
    { Date: 'Tue Oct 01 2019' },
    { Date: 'Tue Oct 01 2019' },
    { Date: 'Tue Oct 01 2019' }, 
    { Date: 'Tue Oct 02 2019' } 
];

const result = data.reduce((total, {Date}) => {
    total[Date] = (total[Date] || 0) + 1;
    return total;
  }, {});
console.log(result);

推荐阅读