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

JavaScript如何从对象数组中按月统计各priority优先级的数量

错误原因

你代码里的问题出在运算符优先级和逻辑判断的写法:&&的优先级低于+,所以(r[key] || 0) + 1 && p2会先完成加法运算得到数字,再和布尔值p2做逻辑与运算,最终返回的结果就是布尔值,这就是你得到true/false的原因。

修复代码

你需要把返回结果的结构调整为每个月份对应一个子对象,子对象内存储各优先级的统计数,修改后的实现如下:

const result = data.reduce((acc, { start_date, priority }) => {
  const monthKey = start_date.slice(0, 7);
  // 首次遇到该月份时初始化各优先级计数为0
  if (!acc[monthKey]) {
    acc[monthKey] = {
      P1: 0,
      P2: 0,
      P3: 0
    };
  }
  // 对应优先级计数+1
  acc[monthKey][priority] += 1;
  return acc;
}, {});
console.log(result);

运行结果

用你提供的测试数据运行后,输出结构如下:

{
  "2018-05": { P1: 1, P2: 0, P3: 0 },
  "2019-05": { P1: 0, P2: 1, P3: 0 },
  "2020-05": { P1: 0, P2: 0, P3: 1 }
}

如果你只需要统计P2优先级的数量,不需要其他优先级的统计,可以简化为下面的写法:

const result = data.reduce((acc, { start_date, priority }) => {
  const monthKey = start_date.slice(0, 7);
  acc[monthKey] = (acc[monthKey] || 0) + (priority === 'P2' ? 1 : 0);
  return acc;
}, {});

内容的提问来源于stack exchange,提问作者mabo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:06:03