如何在使用...new Set()去重后的数组中添加重复值计数
问题:为分数数组添加重复计数并转为指定格式对象数组
我从API获取了包含重复值的数学分数数组,目前用...new Set()实现了去重,但希望最终数组里能同时包含每个分数的重复次数,格式要求是类似[{10: 3}, {15: 5}...]的对象数组,方便后续渲染数据。
当前去重代码:
let notes = []; if (props.getAllNotes()) { const maths = props.getAllNotes().map(item => { return item.subjects[0].math_note }); notes = [...new Set(maths)]; }
提取后的原始分数数组:
[15,16,10,13,15,16,10,18,11,13,15,16,10,18,11];
我知道可以用reduce生成计数对象,但不清楚如何将结果处理成目标格式的数组。
解决方案
完整实现代码
let notes = []; if (props.getAllNotes()) { // 提取所有数学分数 const maths = props.getAllNotes().map(item => item.subjects[0].math_note); // 统计每个分数的出现次数 const countObj = maths.reduce((acc, score) => { acc[score] = (acc[score] || 0) + 1; return acc; }, {}); // 转换为目标格式的对象数组 notes = Object.entries(countObj).map(([score, count]) => ({ [score]: count })); }
代码说明
- 提取分数:通过
map从API返回的数据中提取所有数学分数,得到原始分数数组; - 统计次数:用
reduce遍历数组,累计每个分数的出现次数,生成一个键为分数、值为次数的对象(比如{15:3, 16:3, 10:3}); - 转换格式:用
Object.entries()把计数对象拆分为键值对数组,再通过map将每个键值对转为单独的对象,最终得到[{15:3}, {16:3}, {10:3}, ...]的目标数组。
内容的提问来源于stack exchange,提问作者Elichy
相关产品推荐
相关产品推荐

