What is the process of calculating the average of JSON data and looping through it multiple times using Javascript?

I've encountered a JSON data set that has the following structure:

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

And so on.

My goal is to calculate the average value of both difficulty and fun for each assignment in the dataset. With 10 sets/individuals and 56 assignments, I plan to filter out the assignments first to get 56 sets with 10 values each for fun and difficulty. Then, I can proceed to calculate the averages.

However, I'm finding it challenging to implement this plan as I'm unsure how to construct this new JSON array effectively. I've considered using map, reduce, and similar functions but have struggled to execute them properly. Is there an easier method to accomplish this task?

Answer №1

To organize the information by task, you can utilize the Array.reduce() method.

After grouping the data accordingly, it becomes possible to calculate the average values 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; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

Provide net.socket as a parameter

What is the best way to pass the net.socket class as an argument in this scenario? Here's my code snippet: this.server = net.createServer(this.onAccept.bind(this)); this.server.listen(this.port); } Server.prototype.onAccept = function () { // Ho ...

Is there a way to customize event property setters such as event.pageX in JavaScript?

Is there a way to bypass event.pageX and event.pageY for all events? This is because IE10+ has a known bug where it sometimes returns floating point positions instead of integers for pageX/Y. ...

Ways to transfer large amounts of data to Amazon Web Services

After reading the node documentation on sqs.sendMessage, I noticed that it mentions the ability to send messages up to 256KB in size. However, my messages tend to exceed this limit. What is the recommended approach for handling large payloads in this scena ...

Node - Creating personalized error handling functions

Currently in the process of developing custom helper methods to eliminate redundancies, utilizing express-promise-router app.js has set up the error handler middleware //errorHandler app.use((err, req, res, next) => { //const error = a ...

Is it possible to remove the for loop from this particular PHP script?

Is it feasible to determine the smallest missing number in a range of whole numbers without utilizing a loop structure? In cases when there are no missing numbers, should the function return the maximum value from the range plus one? This is how I approac ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Using the WooCommerce API to handle multi line JSON data

I've experimented with various solutions to make this function properly. text1\ntext2 text1\\ntext2 text1\r\ntext2 Unfortunately, none of these methods have worked. After manually creating a product in WordPress with mul ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

What is preventing me from using .bind(this) directly when declaring a function?

Consider the code snippet below: function x() { this.abc = 1; function f1() { alert(this.abc); }.bind(this) var f2 = function b() { alert(this.abc); }.bind(this); } I am curious about how to make the "this" of the out ...

Display a webpage containing error messages and user input that can be sent back to the AJAX request

My form collects user information such as name, surname, etc. Here is an example of one input field: <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" value= ...

Fetching JSON data from a script tag in Java: What is the best way?

My objective is to extract the JSON value from a script tag on a webpage. The challenge lies in the fact that the JavaScript tag contains numerous functions alongside a JSON array. I have managed to convert the entire script into string format using jsoup, ...

Change the color of the border to match the background color

I have a parent container with a unique background color. Inside the parent container, there is an unordered list (ul) with multiple list items (li), each having a distinct color and a brighter border color. Now, I am looking to extract the border color of ...

How to retrieve only the last value from a JSON object using jQuery's .html

I'm having an issue with jQuery("#someID").html. It seems to only display the last name from the JSON data. Here is the javascript code: <div class="row" id="fetchmember"> <script type="text/javascript"> jQuery('#group').cha ...

monitoring the winstonjs logs and inserting additional parameters

Can an argument be injected into a log, like error, debug, or info, using the configuration of winston (createLogger)? I want to intercept the log and include an object in each log entry. ...

Include and remove JSON data items within ng-repeat loop

I am in the process of creating a dynamic page where users can add multiple locations to their contact information. Currently, my code looks like this: <div class="input-append" ng-repeat="location in newPartner.partner_location"> <input clas ...

Both the maxlenght and ng-maxlength directives appear to be ineffective in AngularJS

In my HTML file, I have the following input: <input name="password" id="newPasswordConfirmation" ng-model="newPasswordConfirmation" type="number" inputmode="numeric" placeholder="" required ...

Syntax Error in Node.js for MongoDB: Unexpected token or invalid symbol

I'm having trouble figuring out what's going on. Node v16.4.2, NPM v7.18.1 const mongoose = require("mongoose"); // const dotenv = require('dotenv') require('dotenv').config({path:'variables.env'}); mongoo ...

Nuxt's dynamic route generation results in a 400 error status code

Currently integrating Nuxt with my app and aiming to establish a connection with my server to retrieve data. To create dynamic routes, I am utilizing the built-in generate method but facing some challenges. Upon executing the generate command, I encounte ...