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

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

Tips for extracting variables from a get OData call function

Is there a better approach to retrieving variables from a GET OData call? I'm struggling with extracting the 'id' variable from the call within my method. I've tried using callbacks, but have not been successful. Do you have any suggest ...

Guide to scraping a website using node.js, ASP, and AJAX

I am currently facing an issue where I need to perform web scraping on this specific webpage form. This webpage is dedicated to vehicle technical reviews, and you can try inputting the car license CDSR70 for testing purposes. As mentioned earlier, I am u ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

The $http Service encounters a failure with an unknown status code

Difficulty Integrating AngularJS, jQuery, and Adobe Panel Creation I recently updated the versions of AngularJS and jQuery for my project. Previously, I was using jquery-1.11.0.min.js and AngularJS 1.2.10. Now, I want to utilize the latest available versi ...

Using JSON to transmit image data stored locally

Currently, I am developing a Java web application with Spring MVC. I have a requirement to send an image of a resource using JSON from local storage located at D:\Work\ResourceData\Employee1\Employee1.jpg to a specific URL. Can anyone p ...

Live notification application using node.js

I am looking to create a recipe maker webapp for practice purposes. This webapp will consist of 2 main pages: the index page and the recipes page. On the "index" page, users can create their own recipes. On the "recipes" page, users can view a table ...

Error: [$controller:ctrlreg] - The controller registration has failed

I am currently exploring the world of AngularJs and attempting to display options from a json file. However, I keep encountering the following error message: "Error: [$controller:ctrlreg]" Below is the code snippet I am working with: var sj = angular. ...

Struggling to align the push menu properly within the Bootstrap framework

I am currently utilizing Bootstrap as my UI framework and attempting to create a push menu on the left side of the page. While I have made progress towards achieving this goal, there are some bugs in the system that I am encountering. Specifically, I am ha ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

One way to verify the existence of an item in a JSON object before pushing it

I am currently working on incorporating offline add to cart functionality. Below is the add to cart function I have: $scope.payloadData = []; $scope.add_to_cart = function(MRP, ProductId, ProductVariantId) { $scope.dt = { //This is a JSON st ...

The error message thrown is: "Unable to assign headers after they have already been sent to the client."

I've been attempting to make a GET request, but it keeps failing at the app.js res.json line. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

Select the Best jQuery Package

Having a variety of packages available for selection. <div class="image-grid-item" data-search="select"> <input name="pack1" type="checkbox" style="display: none;"> </div> <div class="image-grid-item" data-search="select"> <inp ...

After fetching, null is returned; however, refreshing the page results in the object being returned. What is the

I have a specific case where I am dealing with an array of 500 post IDs and I need to retrieve the first 100 posts. To achieve this, I implemented the following code: API https://github.com/HackerNews/API BASE_URL = 'https://hacker-news.firebaseio.com ...