Home > Enterprise >  How do you calculate the average of JSON values and iterate this x amount of times with Javascript?
How do you calculate the average of JSON values and iterate this x amount of times with Javascript?

Time:08-20

I have a JSON data set which looks like this:

 {
   name: "Evelyn",
   assignment: "SCRUM",
   difficulty: 3,
   fun: 4
 }

Etc.

I am trying to calculate the average of the difficulty and fun values for each assignment. Because I have 10 sets/individuals with 56 assignments, my idea is to first filter on the assignments which should produce 56 sets of assignments with 10 values for each fun and difficulty and then calculate the average for each.

I am struggling with putting this plan into action because I do not know how to make this new JSON data set/array decently. I am thinking about map, reduce etc. but simply struggle putting it into action. Is there a simple way to do this?

CodePudding user response:

You can group the data by assignment, using Array.reduce().

Once we've grouped the data, we can get the average for both difficulty and fun.

let data = [{ name: "Evelyn", assignment: "SCRUM", difficulty: 3, fun: 4 }, { name: "Bill", assignment: "SCRUM", difficulty: 1, fun: 3 }, { name: "Carol", assignment: "SCRUM", difficulty: 2, fun: 5 }, { name: "Evelyn", assignment: "PLANNING", difficulty: 5, fun: 3 }, { name: "Bill", assignment: "PLANNING", difficulty: 6, fun: 1 }, { name: "Carol", assignment: "PLANNING", difficulty: 1, fun: 2 } ]
 
const groupedData = Object.values(data.reduce((acc, { name, assignment, difficulty, fun }) => { 
     acc[assignment] = acc[assignment] || { assignment, difficulty: 0, fun: 0, participants: 0 };
     acc[assignment].difficulty  = difficulty;
     acc[assignment].fun  = fun;
     acc[assignment].participants  ;
     return acc;
}, {}))

const result = groupedData.map(({ assignment, participants, difficulty, fun }) => { 
    return { 
        assignment,
        participants,
        averageDifficulty: difficulty / participants,
        averageFun: fun / participants
    }
});
 
console.log(result)
 
.as-console-wrapper { max-height: 100% !important; }

  • Related