如何基于第二个数组统计目标数组对应元素的出现次数并包含0值项
完全可以结合grade数组用reduce实现,推荐直接以grade数组作为reduce的遍历对象,天然保证输出key的顺序和grade完全一致,同时自动补全未出现的项为0:
方法1:简单实现(适合小规模数组)
const result = grade.reduce((acc, key) => { // 统计arr中当前key的出现次数 acc[key] = arr.filter(item => item === key).length; return acc; }, {});
方法2:高性能实现(适合大规模数组)
仅遍历arr一次,时间复杂度更低:
// 第一步:先统计arr中属于grade的元素计数 const countMap = arr.reduce((acc, val) => { if (grade.includes(val)) { acc[val] = (acc[val] || 0) + 1; } return acc; }, {}); // 第二步:按grade的顺序生成最终结果,未出现的项默认补0 const result = grade.reduce((acc, key) => { acc[key] = countMap[key] || 0; return acc; }, {});
两种方法最终输出都符合要求:
{ '13B': 0, '13A': 0, '12D': 3, '12C': 5, '12B': 7, '12A': 12 }
内容的提问来源于stack exchange,提问作者MayaGans
相关产品推荐
相关产品推荐

