Good morning, after an array.map I have an array containing the same assignments with some nested ratings:

const assignments = [
    {
      name: "assignmentOne",
      difficultyRating: 1,
      funRating: 2
    },
    {
      name: "assignmentOne",
      difficultyRating: 3,
      funRating: 4
    },
    {
      name: "assignmentOne",
      difficultyRating: 5,
      funRating: 1
    }
]

Now I would like to get the total difficulty/fun rating, which would look like one of the following:

//Both the difficulty and fun rating in the same record
const assignmentsTotal = [
    {
      name: "assignmentOne",
      totalDifficultyRating: 9,
      totalFunRating: 7
    }
]

//Difficulty and fun rating as separate records
const assignmentsDifficultyTotal = [
    {
      name: "assignmentOne",
      totalDifficultyRating: 9
    }
]
const assignmentsFunTotal = [
    {
      name: "assignmentOne",
      totalFunRating: 7
    }
]

I’m pretty confident the best way to do this is using the reduce method. After some digging around the only thing that came close to what I want to achieve is the following article, yet I’m not able to get this to work properly. Is there a good way to do this from the starting point above, or would it be better to create separate arrays using array.map and after use the reduce method?

Answer

If you are looking for same ‘name’ objects in array, below should be ok:

const reducer = assignments.reduce((total, current) => {
    return { name: current.name, difficultyRating : total.difficultyRating + current.difficultyRating, funRating : total.funRating + current.funRating } });

if you want to group objects by name, then look at lodash groupby function. In general, lodash is very handy in all array/obj functionalities.