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

Creating a dynamic display of flash files on a webpage through a unique combination of PHP, AJAX, and

Despite my lack of experience with Ajax and minimal java knowledge, I have a strong background in SQL and PHP. Even though I anticipate criticism for this question, I am determined to seek help. My primary objective is to rotate 4 flash SWF files randomly ...

Searching for single and double quotes within a string using RegExp in JavaScript

I have encountered an issue while searching for a substring within a string using the code below: mystring.search(new RegExp(substring, 'i')) The reason I am utilizing new RegExp is to perform a case-insensitive search. However, when the string ...

Having trouble getting the vue-slick-carousel to function properly when using it from the CDN

Struggling to implement a small app using the CDN script at , but so far no success. I'm a novice with vue.js and unsure if I need to import anything. According to the documentation, importing is required: Vue-slick-carousel Following this structure ...

Using Plotly.js within a deleted Vue.js component may result in displaying an incorrect chart

Issue I am facing a problem with deleting one of the components that contains a chart. Even after deleting the component, the chart remains visible. To see an example, check out this jsfiddle: https://jsfiddle.net/m4ywp5fc/4/ Solution Attempted I attem ...

Utilize JSON data in d3.js for creating a scatterplot visualization

I have recently started working with d3.js and I'm facing some challenges. From what I understand, the second parameter passed in d3.json() is used to process data from a JSON file. Here is my code: d3.json(base_url() + "data/data.json", clean_data) ...

Steps for accessing the files uploaded in a React application

Looking to implement an upload button using material UI that allows users to upload multiple files, with the goal of saving their paths into an array for future use. However, I'm unsure about where these uploaded files are stored. The code snippet be ...

Does Chrome have a feature that disables event listeners?

I'm currently working on a tool that incorporates file drag and drop functionality. Strangely, this feature works perfectly in all browsers except for Chrome. Surprisingly, however, it does work in Chrome when the tool is run locally. Here is the cod ...

PHP Brandwatch HTTP API Request

Upon making an API request, a server response in JSON format is returned as a single string: {"resultsTotal":3,"resultsPage":-1,"resultsPageSize":-1,"results":[{"id":1998425622,"name":"Regionale Mentions_Branche","type":"search string","creationDate":"201 ...

When utilizing JSON data in web services, I am presented with a variety of information. However, I am only interested in extracting the ID and

When I retrieve data using JSON in web services, the output includes various attributes. What I am interested in extracting are only the 'id' and 'agenda_temp' data. { "0": "1", "1": "Travel Plan", "id": "1", "agenda_temp": "Tr ...

Combining PHP Arrays into a Single Array

Hello everyone, I have this specific output that I need to transform. Here is the initial output: string(47) "[{"value": "["Mouse","Cable Lock","Headset"]"}]" This is how I want it to look: " ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

Incorporate a division based on the selection made from a jQuery dropdown menu

Is there a way to dynamically display a div to the right of a drop-down menu based on the user's selection using DOM manipulation? For reference, you can view an example of my current progress here: http://jsbin.com/#/afojid/1/edit The initial drop ...

QUnit and a troubleshooting JSONP situation

I am currently working on testing my web app's ability to handle failure scenarios and display the corresponding error messages using QUnit. One particular scenario I am focusing on is when my Data Source is unavailable during app initialization, res ...

What is the best way to ensure NPM package manager points to my custom version of a library?

Looking to address a bug in an NPM library. Seeking guidance on configuring my software to point to my customized version of the library using package.json instead of the generic version from npmjs.org. This way, I can effectively debug my own iteration o ...

Combining two states in the Vuex store

In my Vuex store, I have two states: notes (synced notes with the server/DB) localNotes (unsynced notes that will move to 'notes' state upon syncing) To display the notes in a list, I use a getter that merges the two objects and returns the me ...

The styles and scripts in Angular.json are not functioning properly

Attempting to integrate Bootstrap into my Angular project, but encountering issues with Scripts and Styles in angular.json After trying to copy the path from the folder, I keep getting errors! "styles": [ "C:\AngularProjects\project1\no ...

Efficiently Measuring the Visibility Area of DetailsList in Fluent UI

I am currently utilizing the DetalisList component alongside the ScrollablePane to ensure that the header remains fixed while allowing the rows to scroll. However, I have encountered a challenge as I need to manually specify the height of the scrollable co ...

Rails Ajax issue encountered

I previously followed a coderwall tutorial on ajax but encountered an ActionController::UnknownFormat error when attempting to open the link in a new tab (Link Name). Can anyone help me figure out what's wrong? Thanks! Additionally, clicking the link ...

Changing the model does not automatically update the visibility of ng-show

I have a fragment of my view that simply displays a loading indicator. Html: <span class="app-loading-container"> <span class="app-loading-animation" ng-show="loading"></span> </span> When I initially load the page, the span ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...