Utilize JavaScript to parse JSON response data, calculate the average of a specified field while keeping track of

The data returned from the API call is structured as follows:

 var array = {"scores":[
      { userid: "1", mark: 4.3 },
      { userid: "1", mark: 3.8 },
      { userid: "2", mark: 4.6 },
      { userid: "2", mark: 4.1 },
      { userid: "2", mark: 3.9 },
      { userid: "2", mark: null}
    ]};

The desired output requires matching each userid with the average of their marks and total count, excluding any null values for mark.

var arr = [
  { userid: "1", mark: 4.05, count: 2 },
  { userid: "2", mark: 4.2, count: 3}
]

I attempted to achieve this with a script, but encountered an error - 'array.scores[0].reduce is not a function'

 result = Array.from(
            array.scores[0].reduce((m, { userid, mark}) => {
                var temp = m.get(userid) || { sum: 0, count: 0 };
                temp.sum += mark;
                temp.count++;
                return m.set(userid, temp);
            }, new Map),
            ([externalCourse, { sum, count }]) => ({ userid, average: sum / count, count })
        );
console.log(result);

Answer №1

By utilizing the Array.prototype.reduce method, it is possible to organize the input data by userid. With this grouped data, calculating the average marks becomes achievable through the following steps.

const input = {
  "scores": [{
      userid: "1",
      mark: 4.3
    },
    {
      userid: "1",
      mark: 3.8
    },
    {
      userid: "2",
      mark: 4.6
    },
    {
      userid: "2",
      mark: 4.1
    },
    {
      userid: "2",
      mark: 3.9
    }
  ]
};

const groupBy = input.scores.reduce((acc, cur) => {
  acc[cur.userid] ? acc[cur.userid].mark.push(cur.mark) : acc[cur.userid] = {
    userid: cur.userid,
    mark: [ cur.mark ]
  };
  return acc;
}, {});
const output = Object.values(groupBy).map((item) => ({
  user_id: item.userid,
  count: item.mark.length,
  avg_mark: item.mark.reduce((acc, cur) => acc + cur, 0) / item.mark.length
}));
console.log(output);

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

Trouble with parsing JSON in PHP

I've been encountering issues with a PHP script I recently created. The problem lies in my inability to retrieve data from a JSON file named demo.json using PHP. Below is the content of the JSON file: { "checkouts":[ { "billing_address":{ ...

transfer a javascript variable with ajax

I am currently developing a website that contains multiple forms, most of which will be submitted using jQuery AJAX. Although I have implemented reCAPTCHA for security reasons, the client is not satisfied with it due to the difficulty in reading the words ...

I constantly encounter the error message "Unable to access properties of undefined (reading 'map')"

I am in the process of using Nextjs 13 for developing my front end and I have a requirement to fetch a .json file from a URL and utilize it to populate my website through server side rendering. However, I keep encountering an error saying "Cannot read prop ...

The PHP server is having trouble accepting a JavaScript object sent via AJAX

Hey there, I'm currently facing an issue with sending fields from a form saved in a JavaScript object to a PHP server. I have set up the AJAX communication, but when I try to access the object in PHP, I notice that the length is showing as 0 during de ...

Can you please explain the concept of straightforward UI routes to me?

I recently discovered that ui-routes are more powerful and advantageous than ngRoutes. In an effort to learn more about the ui-routing feature, I started studying from http://www.ng-newsletter.com/posts/angular-ui-router.html. However, I found it challengi ...

Instead of displaying the decoded information, an error is being printed during the JSON decoding process

Trying to retrieve author and download_url from the JSON Array provided below. [ { "id": "0", "author": "Alejandro Escamilla", "width": 5616, "height": 3744, "url": "https://unsplas ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

Tips for sending form data from ReactJS to controller in ASP.NET MVC:

Seeking help with React and ASP.NET integration. I am attempting to create a form in ASP.NET using React, but encountering issues when trying to pass form data from ReactJS to an MVC ASP.NET controller. Below is the code that I have been working on. Any su ...

I am encountering an issue where pagination is not functioning correctly while applying filters. Can anyone suggest a

I am currently experiencing an issue with my datatable. The result and pagination function correctly, however, when I apply a filter, the pagination does not adjust accordingly. This seems to be a common problem on this type of page. Even after filtering, ...

Alter the row's color using the selection feature in the module

Is there a way to change the color of a row when a specific property has a certain value? I found a solution for this issue on Stack Overflow, which can be viewed here: How to color row on specific value in angular-ui-grid? Instead of changing the backgro ...

Jackson: When converting a JSON string response to POJO using Jackson, make sure to filter out any null or blank values

Currently, I am using Jackson to convert a JSON response into a List of Pojo objects. Here is the sample response: [ { "code": "", "total": 24, "name": null }, { "code": "", "total": 1, "name": " ...

JavaScript Instant Validation: Ensuring Accuracy in Real-Time

I am trying to create a JavaScript code that validates user input based on certain rules. If the input does not meet the criteria, I want an error message to appear next to the text field. For instance, if the rule is that the first character must be a cap ...

Reduce the size of your Javascript files to the earliest possible version

Any suggestions for converting minimized JavaScript to earlier versions? Are there any tools or websites available for this task? Thank you in advance for any hints. ...

Utilizing checkboxes to toggle the visibility of a div element with varying headings

By toggling a checkbox, I aim to show or hide the same div with a different heading. $('#cbxShowHide').click(function() { this.checked ? $('#block').show(1000) : $('#block').hide(1000); }); #block { display: none; bac ...

Creating background color animations with Jquery hover

<div class="post_each"> <h1 class="post_title">Single Room Apartments</h1> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb last" ...

Dealing with nested try/catch mechanism in NodeJS

As a Node.js novice, I am delving into the realm of coding two nested try/catch blocks with retry logic. My goal is to have the inner try/catch block send any caught errors to the outer catch block, where I will increment a retry count by 1. Once this co ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

Meteor Routing Issue: The path "/"" you are trying to access does not exist in the routing system

After upgrading Meteor to version 1.3.2.4, I encountered an issue where the error message "Error : There is no route for the path: /" appeared. I made sure to update all packages to their latest versions as well. I tested the application in both "meteor" ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...