javascript - 数组分组和计数
问题描述
我正在尝试从以下数据示例中获取每日计数:
{ '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);
解决方案
如果我对您的理解正确,您想要的是分组并获得计数:
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);
推荐阅读
- android - 访问优先保存的其他应用程序的数据
- json - 使用 SSMS 连接 Azure Blob 存储 JSON 数据
- python - VSCode:尽管安装了插件,python linting 仍无法正常工作
- flutter - 在标签栏中添加垂直线作为分隔线作为分隔线
- java - 如何管理 Microsoft Graph SDK 的 AccessToken 的自动刷新(使用 Google oauth2 库管理身份验证)
- java - 列出异常 java.lang.UnsupportedOperationException
- java - 使用多个常量字段
- android - Xamarin Forms 如何更改我在底部导航区域中使用的 png 图标的颜色?
- tensorflow - 如何使用 scatter_update 更新张量流对角权重矩阵
- java - 如何避免连字符拆分正则表达式?