如何对JavaScript数据数组按月份进行分组?
按月份分组数组元素的实现方案
原始数组
const myArray = [{ date: "2017-01-01", Name: "test1" }, { date: "2017-01-02", Name: "test2" }, { date: "2017-02-04", Name: "test3" }, { date: "2017-02-05", Name: "test3" } ]
目标格式
const myArray = [{ group: "Jan", data: [{ date: "2017-01-01", Name: "test1" }, { date: "2017-01-02", Name: "test2" } ] }, { group: "Feb", data: [{ date: "2017-02-04", Name: "test3" }, { date: "2017-02-05", Name: "test3" } ] } ]
实现代码
通过reduce方法结合月份映射表即可完成分组转换:
// 月份英文缩写映射表,对应Date.getMonth()返回的0-11索引 const monthAbbrs = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const groupedArray = Object.values(myArray.reduce((acc, item) => { // 提取当前元素日期的月份索引 const monthIndex = new Date(item.date).getMonth(); const monthName = monthAbbrs[monthIndex]; // 初始化对应月份的分组 if (!acc[monthName]) { acc[monthName] = { group: monthName, data: [] }; } // 将元素加入对应分组的data数组 acc[monthName].data.push(item); return acc; }, {})); console.log(groupedArray);
代码说明
- 月份映射:提前定义好月份数字到英文缩写的对应关系,适配
Date.getMonth()返回的0起始索引值。 - 分组逻辑:用
reduce遍历数组,将每个元素根据月份归类到对应的分组对象中。 - 格式转换:通过
Object.values()将分组后的对象转为数组,得到目标格式的结果。
内容的提问来源于stack exchange,提问作者Bernard
相关产品推荐
相关产品推荐

