I have two arrays. I would like to get the sum of time_spent field if course_id is same in arr1 as well as if course_id matches the id field of arr2
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 },
];
// expected result
newArr = [
{ instructor_id: 7, course_id: 19, time_spent: 0 },
{ instructor_id: 7, course_id: 20, time_spent: 120 },
];
CodePudding user response:
There are many ways to do this, and although you didn't fully specify what should happen with all the fields, there is a straightforward way to use Array reduce to perform a selective sum.
As a clever shortcut, you can multiply a value by a boolean to sum up only matching values by adding 0 for non-matching items. condition * value
is equivalent to the ternary condition ? value : 0
const 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 },
];
const arr2 = [
{ id: 19, title: "Course 19", duration: 180 },
{ id: 20, title: "Course 20", duration: 120 },
];
const result = arr2.map(({ id }) => ({
course_id: id,
time_spent: arr1.reduce(
(prev, cur, index) => prev (cur.course_id == id) * cur.time_spent
, 0)
}));
console.log(result);