Attempting to extract the desired aggregations from a two-dimensional JSON array

Looking to parse through this JSON 2D array (snapshot data example below) to calculate the total cases and deaths for each date, disregarding the state column. While achievable in SQL, it poses a challenge in JavaScript.

Ultimately, the summarized data will resemble:

The JSON 2D array will take the following form:

{date: "2020-02-17", totalCases: "7", totalDeaths: "1"}
{date: "2020-02-18", totalCases: "150", totalDeaths: "2"}
{date: "2020-02-19", totalCases: "210", totalDeaths: "3"}
{date: "2020-02-20", totalCases: "350", totalDeaths: "7"}

The original JSON object to aggregate is shown below

138: {date: "2020-02-18", state: "California", fips: "06", cases: "7", deaths: "0"}
139: {date: "2020-02-18", state: "Illinois", fips: "17", cases: "2", deaths: "0"}
140: {date: "2020-02-18", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"}
141: {date: "2020-02-18", state: "Nebraska", fips: "31", cases: "10", deaths: "0"}
142: {date: "2020-02-18", state: "Texas", fips: "48", cases: "2", deaths: "0"}
143: {date: "2020-02-18", state: "Washington", fips: "53", cases: "1", deaths: "0"}
144: {date: "2020-02-18", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"}
145: {date: "2020-02-19", state: "Arizona", fips: "04", cases: "1", deaths: "0"}
146: {date: "2020-02-19", state: "California", fips: "06", cases: "7", deaths: "0"}
147: {date: "2020-02-19", state: "Illinois", fips: "17", cases: "2", deaths: "0"}
148: {date: "2020-02-19", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"}
149: {date: "2020-02-19", state: "Nebraska", fips: "31", cases: "10", deaths: "0"}
150: {date: "2020-02-19", state: "Texas", fips: "48", cases: "2", deaths: "0"}
151: {date: "2020-02-19", state: "Washington", fips: "53", cases: "1", deaths: "0"}
152: {date: "2020-02-19", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"}
153: {date: "2020-02-20", state: "Arizona", fips: "04", cases: "1", deaths: "0"}
154: {date: "2020-02-20", state: "California", fips: "06", cases: "8", deaths: "0"}
155: {date: "2020-02-20", state: "Illinois", fips: "17", cases: "2", deaths: "0"}
156: {date: "2020-02-20", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"}
157: {date: "2020-02-20", state: "Nebraska", fips: "31", cases: "11", deaths: "0"}

Answer №1

If you want to achieve this, consider utilizing the reduce method.

const data = {
138: {date: "2020-02-18", state: "California", fips: "06", cases: "7", deaths: "2"},
139: {date: "2020-02-18", state: "Illinois", fips: "17", cases: "2", deaths: "0"},
140: {date: "2020-02-18", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"},
141: {date: "2020-02-18", state: "Nebraska", fips: "31", cases: "10", deaths: "0"},
142: {date: "2020-02-18", state: "Texas", fips: "48", cases: "2", deaths: "0"},
143: {date: "2020-02-18", state: "Washington", fips: "53", cases: "1", deaths: "2"},
144: {date: "2020-02-18", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"},
145: {date: "2020-02-19", state: "Arizona", fips: "04", cases: "1", deaths: "0"},
146: {date: "2020-02-19", state: "California", fips: "06", cases: "7", deaths: "0"},
147: {date: "2020-02-19", state: "Illinois", fips: "17", cases: "2", deaths: "0"},
148: {date: "2020-02-19", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"},
149: {date: "2020-02-19", state: "Nebraska", fips: "31", cases: "10", deaths: "0"},
150: {date: "2020-02-19", state: "Texas", fips: "48", cases: "2", deaths: "0"},
151: {date: "2020-02-19", state: "Washington", fips: "53", cases: "1", deaths: "0"},
152: {date: "2020-02-19", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"},
153: {date: "2020-02-20", state: "Arizona", fips: "04", cases: "1", deaths: "0"},
154: {date: "2020-02-20", state: "California", fips: "06", cases: "8", deaths: "0"},
155: {date: "2020-02-20", state: "Illinois", fips: "17", cases: "2", deaths: "0"},
156: {date: "2020-02-20", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"},
157: {date: "2020-02-20", state: "Nebraska", fips: "31", cases: "11", deaths: "0"}
};

const result = Object.values(data).reduce((acc, {date, cases, deaths}) => {
 if (acc[date] !== undefined) {
    acc[date].totalCases += (+cases);
    acc[date].totalDeaths += (+deaths);
 } else {
    acc[date] = {date, totalCases: (+cases), totalDeaths: (+deaths)};
 }

 return acc;
}, {});

console.log(result);
.as-console-wrapper {min-height: 100% !important; top: 0;}

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

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

How can I retrieve key-value pairs from a JSONB column in PostGreSQL?

I am working with a postgresql database that includes a column storing JSON objects in the jsonb format. I have encountered a situation where I need to retrieve a specific key-value pair from the json object, but I have been unsuccessful in finding releva ...

What is causing the error message 'Unexpected use of 'location' no-restricted-globals'?

When working on my reactjs code, I encountered the following issue: const { children, location: { pathname }, } = this.props; let path = location.pathname; I am also utilizing the react router module in this component. Anyone have suggestions on how ...

Troublesome code with Ajax, Jquery, and PHP is causing issues

I've been trying to send an array from php to js using ajax, but for some reason it's not working no matter what I try. I'm convinced it must be a simple fix, but I seem to have exhausted all my options. <!doctype html> <html lang= ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

JQuery fails to remove the "display:hidden" attribute

List of methods I attempted: Utilizing .removeClass and addClass functions Applying show() and hide() methods Modifying the CSS properties Initially, I confirmed that my script contains onLoad. Furthermore, all other elements are functioning correctly. D ...

Including a JavaScript file in an HTML document initiates a server request, which can lead to potential errors

I am currently developing a web application using Express and Node.js on the backend, with EJS as the templating engine on the frontend. Here is a snippet of my app.js file: app.get('/book/:id', (req, res)=>{ var book_id = req.params.id; cons ...

Preventing preventDefault() from firing in JQuery only when necessary

I have come up with a script that I recently created. <script> $(document).ready(function(){ $('a').data('loop',true); $('body').on('click', 'a', function(event){ console.lo ...

What is the best way to receive a sanitized output from a POST request and store it in a JSON file?

In my nodejs and hapi framework, I have the following code for handling a POST request: server.route({ method: "POST", path: "/newdata", config: { validate: { query: Joi.object({ ...

What is the process to obtain the download URL for an image stored in Firebase Storage?

I have encountered an issue while trying to upload an image to Firebase storage and then retrieve the download URL. Here is the code snippet that I am using: const response = await fetch(selectedImage.uri); const file = await response.blob(); const storag ...

Adjust the visual presentation based on the chosen option at the top of a column JQchart

Can anyone offer assistance with creating three radio button fields that will display yearly, monthly, or weekly data on a column chart? I have searched through numerous examples in JQchart but haven't found one for this specific scenario. Are there o ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

What is the best way to generate a linked list from a JSON array?

I have a list of universities that I generated from a JSON file and now I want to create hyperlinks for each university in the list so that users can navigate to their respective university pages. HTML <ul data-bind="foreach: university"> <li ...

How can I attach a cookie to a div that becomes visible after a few seconds of video playback?

After 20 seconds of video play, a div element appears. I am trying to set up a cookie so that once the div is shown, it continues to appear unless the user clears their cache (cookie logic). This is my current attempt - http://jsfiddle.net/9L29o365/ Any ...

Challenges when upgrading from Ext JS 3 to Ext JS 4

I am looking to upgrade my code from Ext JS 3 to Ext JS 4. I used the Ext.Updater class in Ext JS 3, but I cannot seem to locate a similar functionality in Ext JS 4. Can anyone provide assistance with this transition? ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Synchronizing two navigation menus on a single-page application website

Let me start by saying that I specialize in back end development and am facing a specific challenge with building a website that includes two navigation menus. The main navigation menu features links like Home, while the sub-navigation menu includes option ...