You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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)

修改后完整代码

仅需两处调整即可满足需求:

  1. 初始化日期分组对象时,新增total字段并设置初始值为0
  2. 每次遍历到对应日期的回答时,同步对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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:39:37