A method for calculating the average of values with identical keys within an object contained in an array

I have a JSON object that contains countries and data values. I need to add up the values of each country and compute their average. Here is the JSON object:

var arraySeries = [{"country":"United States","data":2},
                   {"country":"Venezuela","data":0},
                   {"country":"Singapore","data":3},
                   {"country":"United States","data":0},
                   {"country":"Germany","data":2},
                   {"country":"United States","data":2},
                   {"country":"Canada","data":2},
                   {"country":"Germany","data":-4}];

Here is the expected result:

var newArraySeries = [{"country":"United States","data":[1.33333]},
                   {"country":"Venezuela","data":[0]},
                   {"country":"Singapore","data":[3]},
                   {"country":"Canada","data":[2]},
                   {"country":"Germany","data":[-1]}];

The data in newArraySeries should be in an array format because I will be using it in my Highchart map. I have searched online but couldn't find any articles on this specific issue. I would really appreciate your help with this.

Answer №1

This challenge was tackled using pure JavaScript and temporary variables

const countryData = {};
const countryDataCount = {};
const updatedSeries = [];

arraySeries.forEach(function(item) {
    if (!countryData[item.country]) {
        countryData[item.country] = 0;
        countryDataCount[item.country] = 0;
    }
    countryData[item.country] += item.data;
    countryDataCount[item.country]++;
});

for (let country in countryData) {
    updatedSeries.push({country: country, data: countryData[country] / countryDataCount[country]});
}

Answer №2

Using the Alasql library, you have the ability to achieve this task.

var dataPoints = [{"country":"United States","data":2},
           {"country":"Venezuela","data":0}];

var result = alasql('SELECT country, AVG(data) AS data FROM ? GROUP BY country',
                  [dataPoints]);

Explore this demonstration on jsFiddle.

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 page you are trying to access does not support the HTTP request method 'GET'. Please try a different method to access the page

I have been attempting to incorporate AJAX for asynchronous communication with the server. However, I keep encountering the following error message. Any insights on how to resolve this issue? org.springframework.web.servlet.PageNotFound.handleHttpReques ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

Creating a simulation of a JavaScript callback within a C# host program

Currently, I am in the process of developing a c# application with an embedded web browser control. In this project, I'm facing a challenge where I need to call a C# method from JavaScript and pass a JavaScript callback using the dynamic technique exp ...

Ways to avoid storing repeating paragraphs in JavaScript Array?

Can someone help me with my code? I am struggling to prevent duplicate data from being saved into an array. When I click on any two paragraph elements, the text inside them gets added to an array named `test`. However, I want to avoid saving the same tex ...

JavaScript or Query: Transforming an Object from an Associative Array

Can someone help me out with converting an associative array into an object in JavaScript? I tried searching on Stackoverflow but couldn't find a working example. Here is the example structure: var combinedproducts = [["Testing-1","test-1"],["Testin ...

Guide to converting JSON with an array into a presenter using a collection

When I retrieve JSON data from an external service regarding trainings for my current_user via email, I receive information like this: { “id:”5357c5d17303b5357c5d173078”, “email”:”<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Is there a way to refresh a Material-UI data table in React whenever a user takes any action?

I am facing an issue with my Lock-Unlock button and delete button. The problem arises when I render data from axios using the useEffect hook, it works fine. However, if I try to lock or unlock a user, the table does not update automatically. This indicates ...

Merge a pair of values into an object using a JOLT conversion

I am new to using Jolt and I have a source format that was generated from some software but it lacks good structure. I want to transform it so that each piece of text ("First text" and "Second text") is associated with a link ("First text -> Link of fir ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Angular JS Visibility Toggling with Ng-Show and Ng-Hide

Working on an angular service for a login form, I've successfully implemented authentication using a factory with an http injector to handle HTTP credentials. However, I'm facing an issue in displaying an error message when incorrect credentials ...

Error encountered: Unknown token '<' and Loading chunk 16 unsuccessful

Having a react app created with create-react-app, I encounter errors whenever I deploy to netlify and there is a new build. Uncaught SyntaxError: Unexpected token '<' 16.0fcd6807.chunk.js:1 Immediately after this error, another one pops up: ...

Deactivate wheel event in jQuery

I am facing a challenge in designing my website using skrollr.js and fullpage.js libraries. Skrollr relies on the value of scrollTop to transform selected elements, while fullpage.js changes the top value of the viewport when scrolling, causing issues with ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

What is the best way to skip certain steps within a Promise using Bluebird?

Here is an example of some code: Queues.findOne({_id: id}) .then(function(q) { var status = q.status; //... }).then(function(q) { // A }).then(function(q) { // B }).then(function(q) { // C }).then(function(q) { // D }).then(function(q) { // E }).then ...

Using a Vue computed property updates the values within the data object

My data structure (this.terms) looks like this: { name: 'First Category', posts: [ { name: 'Jim James', tags: [ 'nice', 'friendly' ] }, ...

Tips for declaring a particular type during the process of destructuring in Typescript

I have my own custom types defined as shown below: export type Extensions = | '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' | '.txt' | '.jpg' | '.csv' | '. ...

How can I implement a jQuery slide down effect for a specific individual instance?

Whenever I click on the "Share your thoughts" button, the comments block slides down for every section instead of just the particular section I clicked on. Is there a way to make it so that only a single block slides down when the button is clicked, regard ...

Slide in the Toggle Effect to Your Navigation Menu

Seeking help with enhancing my jQuery dropdown menu to include a slide down toggle effect similar to this example: http://jsfiddle.net/LaSsr/188/. Any assistance in applying this slide effect to the following JSfiddle would be greatly appreciated. Thank yo ...

Tips for creating a multi-step wizard using AngularJS and incorporating AJAX calls---Crafting a multi

Exploring the creation of a multi-step wizard with ajax calls: Utilizing ui.router for managing views of the wizard steps, the first page prompts users to input data such as playerid. The second page aims to display information retrieved from the server b ...

The Safari 7.1+ browser seems to be having trouble with the spotlight effect

Why is the CodePen not functioning properly in Safari? Despite working well in Chrome and Firefox, it completely fails to work in Safari 7.1+. Can anyone provide some insights? http://codepen.io/cchambers/pen/Dyldj $(document).on("mousemove", function( ...