如何使用ES6或reduce统计对象数组指定属性的分组数量?
按对象属性分组并统计唯一分组数量的ES6实现
嘿,这个需求其实挺常见的,我给你分享两种简洁的ES6写法,都能快速得到你要的结果:
方法一:利用 reduce 生成分组标记
我们可以用reduce遍历数组,把每个group的值作为键存入累加器对象(只需要标记存在即可,不用统计具体个数),最后通过Object.keys()获取所有唯一分组的键,再取长度就是结果:
const arr = [ { group: 1 }, { group: 2 }, { group: 2 } ]; const uniqueGroupCount = Object.keys( arr.reduce((acc, item) => { acc[item.group] = true; // 标记该分组存在 return acc; }, {}) ).length; console.log(uniqueGroupCount); // 输出:2
如果之后你还需要知道每个分组的具体元素数量,可以稍微调整reduce的逻辑,改成计数模式,最后再取键的长度:
const arr = [ { group: 1 }, { group: 2 }, { group: 2 } ]; const groupCountMap = arr.reduce((acc, item) => { acc[item.group] = (acc[item.group] || 0) + 1; // 统计每个分组的元素数 return acc; }, {}); const uniqueGroupCount = Object.keys(groupCountMap).length; console.log(groupCountMap); // 输出:{1: 1, 2: 2} console.log(uniqueGroupCount); // 输出:2
方法二:利用 Set 自动去重(更简洁)
ES6的Set天生具备去重特性,我们可以先通过map提取所有group的值,再传入Set生成唯一值集合,最后取size属性就是唯一分组的数量:
const arr = [ { group: 1 }, { group: 2 }, { group: 2 } ]; const uniqueGroupCount = new Set(arr.map(item => item.group)).size; console.log(uniqueGroupCount); // 输出:2
这种写法代码更短,适合只需要统计唯一分组数量的场景。
内容的提问来源于stack exchange,提问作者Miyagiborn
相关产品推荐
相关产品推荐

