求实现统计JSON对象中课程名称及出现次数的函数
解决课程名称统计问题
没问题,我来帮你实现这个课程名称的统计功能!核心思路是先用一个对象记录每个课程的出现次数,再把这个对象转换成你需要的数组格式。
完整实现代码
let json = { "0": "advanced-data-structures", "1": "advanced-data-structures", "145": "advanced-data-structures", "149": "advanced-excel", "185": "advanced-excel", "186": "advanced-r", "202": "advanced-r", "203": "advanced-r", "204": "advanced-trading-algorithms", "205": "advanced-trading-algorithms", "206": "agile-planning-for-software-products", "276": "agile-planning-for-software-products", "277": "agile-planning-for-software-products", "278": "algorithmic-thinking-1", "282": "algorithmic-thinking-1", "283": "algorithmic-thinking-1" }; function getCourseCounts(courseObj) { // 用对象存储每个课程的出现次数 const courseCounts = {}; // 遍历所有课程值,更新计数 Object.values(courseObj).forEach(course => { if (courseCounts[course]) { courseCounts[course]++; } else { courseCounts[course] = 1; } }); // 将计数对象转换为要求的数组格式:[课程名, 次数] return Object.entries(courseCounts); } // 调用函数并输出结果 const result = getCourseCounts(json); console.log(result);
代码解释
- 步骤1:创建计数对象:
courseCounts用来临时存储每个课程的出现次数,键是课程名称,值是对应的次数。 - 步骤2:遍历统计:通过
Object.values(json)拿到所有课程名称的数组,遍历每个课程时:- 如果课程已经在
courseCounts里,就把次数加1 - 如果是第一次遇到,就把次数初始化为1
- 如果课程已经在
- 步骤3:转换格式:
Object.entries(courseCounts)会把对象转换成[key, value]的数组格式,刚好符合你需要的["课程名", 次数]结构。
输出结果
运行代码后,你会得到如下格式的结果:
[ ["advanced-data-structures", 3], ["advanced-excel", 2], ["advanced-r", 3], ["advanced-trading-algorithms", 2], ["agile-planning-for-software-products", 3], ["algorithmic-thinking-1", 3] ]
另外,你的原有代码里的arrayOfCourses、uniqueItems和for循环其实可以不用,用上面的方法更简洁高效哦~
内容的提问来源于stack exchange,提问作者Murshid Hassen
相关产品推荐
相关产品推荐

