You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求实现统计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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:17:57