如何从给定数组统计各月份订单数量(含无订单月份)
统计全年各月订单数量(无订单月份显示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}]
解决方案
通过以下步骤实现需求:
- 定义与预期输出匹配的月份列表
- 统计现有数据中各月份的订单数量
- 遍历月份列表生成结果,无订单月份填充为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
相关产品推荐
相关产品推荐

