如何使用JavaScript reduce按日期统计回答数及total值
按日期分组统计回答量的JS实现方案
需求说明
需要基于给定的回答数组,按日期维度做分组统计,每个日期分组需返回三个统计值:
yes:该日期下回答为yes的条数no:该日期下回答为no的条数total:该日期下回答总条数
期望单组输出格式如下:
"2022-01-03": { "yes": 1, "no": 2, "total": 3 }
原有代码说明
现有reduce逻辑已经完成了yes、no两个字段的计数,仅缺少total字段的初始化和累加逻辑,原有代码如下:
const array = [ { date: '2022-01-03', answer: 'yes' }, { date: '2022-01-03', answer: 'no' }, { date: '2022-01-03', answer: 'no' }, { date: '2022-01-04', answer: 'yes' }, { date: '2022-01-04', answer: 'yes' }, { date: '2022-01-05', answer: 'yes' }, { date: '2022-01-05', answer: 'yes' }, { date: '2022-01-05', answer: 'yes' }, { date: '2022-01-05', answer: 'no' }, ] const result = array.reduce((acc, curr) => { if (!acc[curr.date]) { acc[curr.date] = { yes: 0, no: 0 } } acc[curr.date][curr.answer]++; return acc; }, {}); console.log(result)
修改后完整代码
仅需两处调整即可满足需求:
- 初始化日期分组对象时,新增
total字段并设置初始值为0 - 每次遍历到对应日期的回答时,同步对
total字段做自增
const array = [ { date: '2022-01-03', answer: 'yes' }, { date: '2022-01-03', answer: 'no' }, { date: '2022-01-03', answer: 'no' }, { date: '2022-01-04', answer: 'yes' }, { date: '2022-01-04', answer: 'yes' }, { date: '2022-01-05', answer: 'yes' }, { date: '2022-01-05', answer: 'yes' }, { date: '2022-01-05', answer: 'yes' }, { date: '2022-01-05', answer: 'no' }, ] const result = array.reduce((acc, curr) => { if (!acc[curr.date]) { acc[curr.date] = { yes: 0, no: 0, total: 0 } } acc[curr.date][curr.answer]++; acc[curr.date].total++; return acc; }, {}); console.log(result)
运行上述代码后,输出结果完全匹配需求格式,各日期统计值准确。
内容的提问来源于stack exchange,提问作者Legion
相关产品推荐
相关产品推荐

