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

如何从给定数组统计各月份订单数量(含无订单月份)

统计全年各月订单数量(无订单月份显示0)

需求说明

现有一组包含订单标识与订单月份的数据对象,需统计每个月份的订单数量,无订单的月份需显示为0。

给定数据

const data = [{
  order: "a",
  date: "Jan"
}, {
  order: "b",
  date: "Jan"
}, {
  order: "c",
  date: "Feb"
}]

预期输出

const orders = [{"Jan":2},
                {"Feb":1},
                {"Mar":0},
                {"Apr":0},
                {"Jun":0},
                {"Jul":0},
                {"Aug":0},
                {"Sept":0},
                {"Oct":0},
                {"Nov":0},
                {"Dec":0}]

解决方案

通过以下步骤实现需求:

  1. 定义与预期输出匹配的月份列表
  2. 统计现有数据中各月份的订单数量
  3. 遍历月份列表生成结果,无订单月份填充为0

完整代码:

const data = [{
  order: "a",
  date: "Jan"
}, {
  order: "b",
  date: "Jan"
}, {
  order: "c",
  date: "Feb"
}];

// 按预期输出定义月份列表(注:预期输出未包含May,此处同步设置)
const targetMonths = ["Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];

// 统计已有数据的各月订单数
const monthCount = data.reduce((countObj, item) => {
  countObj[item.date] = (countObj[item.date] || 0) + 1;
  return countObj;
}, {});

// 生成最终结果数组
const orders = targetMonths.map(month => ({
  [month]: monthCount[month] || 0
}));

console.log(orders);

代码说明

  • 用reduce遍历原始数据,将每个月份的订单数累加存储在对象中
  • 用map遍历目标月份列表,对每个月份,若已统计到订单数则使用该数值,否则填充为0,同时生成单个键值对的对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:50:25