Compare two arrays of objects JS

Viewed 54

I have two arrays which consist of custom made objects. They look like the following:


courses: [
{Course: "Design", ECST: 5}, 
{Course: "Construction", ECTS: 10}
],

statistics: [
{Course: "Design", Hours: 2}, 
{Course: "Design", Hours: 2}, 
{Course: "Construction", Hours: 2},
{Course: "Construction", Hours: 2},
],


I want to calculate the sum of hours from the "statistics" array of each Course. The problem is that the user adds the courses, so I can not say === "Design", but I have to compare them based on the courses added. So my questions is this: How can I calculate the total amount of Hours from each course in the "statistics" Array? Is there a way to simply compare the courses allready added? Something like all courses which equals each other, get the hours?

2 Answers

I'm not sure I fully understood your problem when reading the question but it sounds like something you probably can solve with a reduce function. In this example we will go through each entry in statistics and combine the hours.

const hoursPerCourse = statistics.reduce((acc, curr) => {
    acc[curr.Course] = acc[curr.Course] ? acc[curr.Course] + curr.Hours : curr.Hours

    return acc
}, {})

You could also get the hours for each course in the course array from this results by doing something like this:

courses.map((course) => ({
    ...course,
    hours: hoursPerCourse[course.Course]
}))

You can simply try like this

Array.prototype.sum = function(matchKey, matchValue, sumKey) {
  var total = 0
  for (var i = 0; i < this.length; i++) {
    if (this[i][matchKey].toLowerCase() === matchValue.toLowerCase())
      total += this[i][sumKey]
  }
  return total
}

console.log(statistic.sum('Course', 'design', 'Hours'))
Related