Combine JSON data into groups based on two keys and calculate the overall count

Searching for a way to organize the JSON Array with 2 keys and calculate the counts of grouped object key using Javascript.

Seeking a solution specifically in Javascript.

Link to Reference

Desired Outcome: the length of the counts object should be limited to 5, showing the total sum of all grouped keys combined.

[
  {
    "totalCount": 3,
    "counts": [0,0,3,0,0],
    "productID": "tea1",
    "keyVal": "key5",
    "trend": "0"
  },
    {
    "totalCount": 4,
    "counts": [2,2,0,0,0],
    "productID": "tea1",
    "keyVal": "key1",
    "trend": "0"
  },
  {
    "totalCount": 11,
    "counts": [0,5,6,0,0],
    "productID": "group1",
    "keyVal": "key2",
    "trend": "0"
  },
  {
    "totalCount": 616,
    "counts": [101,507,8,0,0],
    "productID": "group1",
    "keyVal": "key1",
    "trend": "0"
 },
]

Answer №1

UPDATE: I inadvertently overlooked the second key

Here is the revised solution:

temp1 = the json data provided in the pasteBin

Adjust the trend variable as the calculation method was not specified.

function groupBy(array, f) {
    var groups = {};
    array.forEach(function(o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
    });
    return Object.keys(groups).map(function(group) {
        return groups[group];
    })
}

var result = groupBy(temp1, function(item) {
    return [item.keyVal, item.productID];
});

var output = [];
result.forEach(grouped => {
    var count = [0, 0, 0, 0, 0];
    var totalCount = 0;
    var trend = 0;
    var productID = grouped[0].productID;
    var keyVal = grouped[0].keyVal;
    grouped.forEach(value => {
        totalCount += value.totalCount;
        value.counts.forEach((x, i) => count[i] += x)
    })
    console.log(count);
    output.push({
        counts: count,
        keyVal: keyVal,
        totalCount: totalCount,
        productID: productID,
        trend: trend
    });
})

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

Is it possible to create a single-page Codeigniter website utilizing both jQuery and AJAX?

Seeking guidance on a unique web design concept: picture this - you visit a website and are initially presented with just a navigation menu. By clicking on items in the menu located on the left side of the screen, different content is revealed on the right ...

Setting up Type ORM configuration with a .env file in Nest.JS: A step-by-step guide

I encountered an issue while attempting to configure TypeORM with a .env file and run migration script. Here's what I tried: 1. Added scripts to package.json "migration:generate": "node_modules/.bin/typeorm migration:generate -n", "migratio ...

Create a full duplication of every field and array within an object using AngularJs with the deepCopy method

I am looking to replicate certain fields within an object in other fields of the same object, similar to the concept demonstrated below: var customers = { apple: { papa: { en: "cool" } }, oranges: { papa: { ...

Pending status persists for Axios post request

Here is a straightforward example of a POST request using Axios within Vue: import axios from 'axios' export default { name: 'HelloWorld', props: { msg: String }, mounted () { const code = 'test&apo ...

Using a series of functions that make use of (theID)

Hey there, I'm new to HTML and I've been trying to achieve something below. Unfortunately, it's crashing and I can't figure out if it's just a syntax error or if what I'm attempting isn't possible. The function declarati ...

Avoid having the browser automatically move focused elements that are navigated to using the tab key

When moving through form elements or anchors using the tab key (and shift + tab), the browser automatically scrolls to the focused element. If the element is not visible due to being part of overflow content with a hidden overflow setting, the container&ap ...

The array is displaying unexpected numerical values

There were two classes utilized in this program - one containing variables and the other using that class as an array. However, when the array is printed, the output appears as [Student@7e0ea639, Student@3d24753a, Student@59a6e353, Student@7a0ac6e3, Stud ...

Hey there! Is there a way to detect in React when the page is rendering due to a ctrl+shift+t command?

Is it possible to detect in React when a page is rendered using the ctrl+shift+t command? I am looking to identify the following scenario: The user closes the browser tab The user then reopens the tab by pressing ctrl+shift+t I want to be able to recogniz ...

What could be the reason for the empty value of driver_execute?

I'm attempting to input text into a textfield using code. binary = FirefoxBinary("C:\Program Files\Mozilla Firefox\Firefox.exe") driver = webdriver.Firefox(firefox_binary=binary) text = 'sending something to the text area' ...

Implementing popup alert for multiple tabs when Javascript session times out

I have implemented javascript setInterval() to monitor user idle time and display a popup alert prior to automatic logout. However, it seems to be functioning correctly only in single tabs. Here is the code snippet: localStorage.removeItem("idleTimeValue ...

How can I create an efficient Java class to model a basic JSON document and handle deserialization effectively?

The current design I have in place for basic messages involves the use of Jackson: public class FooRequest { public final String foo; public final int bar; @JsonCreator public FooRequest( @JsonProperty("foo") String foo, ...

Tips on implementing {% csrf_token %} with javascript

On my users page, I have implemented editing with ajax. Initially, the edit function works fine but upon submitting the form, nothing happens. The error message revealed that: CSRF verification failed. Request aborted. Could someone guide me on how to in ...

React: Incorporating .map for nested arrays. Ensure each child component within the list is assigned a distinct "key" property

I have an array called navMenuItems that contains data for building a navigation menu with links and link names. Each item in the array may also contain child links, similar to the mobile menu on https://www.w3schools.com/. However, I'm encountering a ...

Transform a collection of dates and times into a string separated by commas, showing the range of values with hyphens

My task involves handling a list of performance dates for an upcoming event. Here is an example of the array: 2014-01-20 20:00:00 2014-01-21 20:00:00 2014-01-22 14:00:00 2014-01-22 20:00:00 2014-01-23 20:00:00 2014-01-25 20:00:00 2014-01-26 20:00:00 2014- ...

Learn the method for automatically checking a checkbox when a page is loaded in Angular

I have multiple checkboxes on a single page <div class="check-outer"> <label>Place of operation</label> <div class="checkDiv"> <div ng-repeat="place in places"> <div class="checkbox-wrapper"> ...

JavaScript: Perform multiplication and addition on two arrays

I am looking for a way to multiply pairs of values in two arrays that have the same length, and then sum up the results based on their indexes. As an example, var arr1 = [2,3,4,5]; var arr2 = [4,3,3,1]; The output would be 34 (4*2+3*3+4*3+5*1). What is ...

Save data from localStorage to clipboard with a click of a button

Imagine you have a total of 25 different names stored in localStorage. How can you easily copy and paste this data from localStorage to clipboard by simply clicking buttons? Take a look at the button code that is designed to copy the localStorage data: & ...

Query for looping through JavaScript: what is the technique for extracting only number elements to create a fresh array?

I have a set of tasks that need to be automated in my daily workflow. The specific task requires: Receiving messages in my IM, and appending the first, second & third number from each link with a "|" delimiter. If there are only 2 numbers in the sequence, ...

Using a string as a key for an object's property

function createObject(argName, argProperties){ var object = {}; object[argName] = argProperties; } I am calling my function in the following manner. createObject('name', objectProperties); The issue I am encountering is w ...

Encountered a CPU-side conversion issue causes Browser to crash when attempting to load an object using threejs

After implementing the code from the threejs example/loader/obj/mtl to load an object exported via Unity3d, some customers have reported browser crashes on their machines. A screenshot of the error message in a browser console can be viewed here. Addition ...