如何使用JavaScript按键对给定数组中的值进行分组?
按Year和Month分组JavaScript数组的实用方案
刚好处理过类似的分组需求,用JavaScript的Array.prototype.reduce()就能轻松搞定——这是处理数组分组最常用也最高效的方法,下面给你几种具体实现:
基础分组实现
先看最直接的写法,把同一year和month的元素归到一起:
const data = [ { "amount": 4.27, "month": 1, "year": 2017 }, { "amount": 2.46, "month": 1, "year": 2017 }, { "amount": 1.5, "month": 2, "year": 2017 }, { "amount": 28.24, "month": 2, "year": 2017 }, { "amount": 8.24, "month": 3, "year": 2017 }, { "amount": 3.65, "month": 3, "year": 2017 }, { "amount": 0.86, "month": 3, "year": 2017 }, { "amount": 0, "month": 1, "year": 2018 }, { "amount": 71.84, "month": 2, "year": 2018 }, { "amount": 26.62, "month": 3, "year": 2018 } ]; // 核心分组逻辑 const groupedData = data.reduce((acc, currentItem) => { // 生成唯一分组键:用year-month拼接,确保同一年月的元素分到同一组 const groupKey = `${currentItem.year}-${currentItem.month}`; // 如果当前键还没在累加器里,初始化一个空数组 if (!acc[groupKey]) { acc[groupKey] = []; } // 把当前元素推入对应分组的数组 acc[groupKey].push(currentItem); return acc; }, {}); // 累加器初始值是空对象 console.log(groupedData);
代码逻辑拆解
reduce会遍历数组里的每一个元素,acc是我们用来存分组结果的“容器”,初始值是空对象。- 每个元素的
year和month拼接成唯一的键(比如2017-1),这样同一年月的元素必然对应同一个键。 - 检查容器里有没有这个键:没有就创建空数组,有就直接把当前元素加进去。
- 最后返回这个容器,就得到了分组好的结果。
进阶:同时计算分组总金额
如果还需要统计每个年月的amount总和,可以稍微改造一下代码,让分组结果更实用:
const groupedWithTotal = data.reduce((acc, currentItem) => { const groupKey = `${currentItem.year}-${currentItem.month}`; if (!acc[groupKey]) { acc[groupKey] = { items: [], // 存该分组的所有元素 totalAmount: 0 // 存该分组的总金额 }; } acc[groupKey].items.push(currentItem); acc[groupKey].totalAmount += currentItem.amount; return acc; }, {}); console.log(groupedWithTotal);
这样你不仅能拿到每个分组的所有原始数据,还能直接获取该年月的总金额,不用再额外遍历计算。
备选方案:用Map存储分组
如果你偏好使用Map(比如需要保持分组的顺序,或者键是更复杂的类型),可以这样实现:
const groupedMap = data.reduce((map, currentItem) => { const groupKey = `${currentItem.year}-${currentItem.month}`; if (!map.has(groupKey)) { map.set(groupKey, []); } map.get(groupKey).push(currentItem); return map; }, new Map()); // 可选:把Map转成普通对象 const groupedObj = Object.fromEntries(groupedMap);
这些方案都能完美解决你的分组需求,根据自己的场景选就行~
内容的提问来源于stack exchange,提问作者Dabber
相关产品推荐
相关产品推荐

