JavaScript按日期分组统计对象数组answer值计数的实现方法
实现方案
你原有代码只完成了按日期分组收集answer值的步骤,没有做计数逻辑,调整reduce内的累加规则即可实现需求,修改后代码如下:
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((prev, curr) => { // 首次遇到当前日期时,初始化和预期格式一致的统计结构 if (!prev[curr.date]) { prev[curr.date] = [{ yes: 0, no: 0 }] } // 对应回答类型的计数直接+1 prev[curr.date][0][curr.answer]++ return prev }, {}); console.log(result)
逻辑说明
- 初始化阶段直接对齐要求的输出结构,不需要先收集answer数组再二次遍历统计,一次循环就能拿到结果
- 每遍历到一条数据,直接根据answer字段值给对应计数项累加,没有多余操作
- 代码运行后输出的结果和预期格式、数值完全匹配
{ "2022-01-03" : [ { "yes": 1, "no": 2 } ], "2022-01-04" : [ { "yes": 2, "no": 0 } ], "2022-01-05" : [ { "yes": 3, "no": 1 } ] }
内容的提问来源于stack exchange,提问作者Legion
相关产品推荐
相关产品推荐

