满足双匹配条件时计算数组time_spent字段的总和
解决方案
要实现需求,我们可以分三步处理:
- 先把arr2中的课程ID提取到集合中,方便快速判断arr1的条目是否需要处理
- 遍历arr1,按「讲师ID+课程ID」分组,累加符合条件条目的
time_spent - 把分组后的结果转换成目标数组格式
具体代码实现如下:
let arr1 = [ { instructor_id: 7, course_id: 19, lesson_id: 1, time_spent: 0 }, { instructor_id: 7, course_id: 19, lesson_id: 2, time_spent: 0 }, { instructor_id: 7, course_id: 19, lesson_id: 3, time_spent: 0 }, { instructor_id: 7, course_id: 20, lesson_id: 4, time_spent: 80 }, { instructor_id: 7, course_id: 20, lesson_id: 5, time_spent: 40 }, { instructor_id: 8, course_id: 21, lesson_id: 6, time_spent: 0 }, ]; let arr2 = [ { id: 19, title: "Course 19", duration: 180 }, { id: 20, title: "Course 20", duration: 120 }, ]; // 提取arr2中的课程ID到集合,提升查询效率 const validCourseIds = new Set(arr2.map(item => item.id)); const grouped = {}; for (const item of arr1) { // 只处理course_id在arr2中存在的条目 if (validCourseIds.has(item.course_id)) { const key = `${item.instructor_id}-${item.course_id}`; if (!grouped[key]) { // 初始化分组对象 grouped[key] = { instructor_id: item.instructor_id, course_id: item.course_id, time_spent: 0 }; } // 累加time_spent grouped[key].time_spent += item.time_spent; } } // 把分组对象转换成数组 const newArr = Object.values(grouped); console.log(newArr);
运行后会得到预期结果:
[ { instructor_id: 7, course_id: 19, time_spent: 0 }, { instructor_id: 7, course_id: 20, time_spent: 120 } ]
代码说明
- 使用
Set存储有效课程ID,判断操作的时间复杂度为O(1),比每次遍历arr2查询更高效 - 用「讲师ID+课程ID」作为分组键,确保同一讲师同一课程的条目被分到一组
- 遍历过程中直接累加
time_spent,最后通过Object.values()将分组对象转换为目标数组格式
内容的提问来源于stack exchange,提问作者Farhan Farooq
相关产品推荐
相关产品推荐

