A guide on how to group by multiple keys and calculate the sum of multiple property values within a JavaScript array using Node.js

Can you suggest the most efficient method to group by multiple keys and calculate the sum of multiple property values in a JavaScript array?

For example:

[ 
    { Category: "Category 1", Subcategory: "Subcategory 1", Value1: "15", Value2: "5" },
    { Category: "Category 1", Subcategory: "Subcategory 2", Value1: "20", Value2: "10" },
    { Category: "Category 2", Subcategory: "Subcategory 1", Value1: "25", Value2: "15" },
    { Category: "Category 2", Subcategory: "Subcategory 2", Value1: "30", Value2: "20" },
    { Category: "Category 1", Subcategory: "Subcategory 1", Value1: "35", Value2: "25" },
    { Category: "Category 1", Subcategory: "Subcategory 2", Value1: "40", Value2: "30" },
    { Category: "Category 2", Subcategory: "Subcategory 1", Value1: "45", Value2: "35" },
    { Category: "Category 2", Subcategory: "Subcategory 2", Value1: "50", Value2: "40" }
]

Desired Result

[ 
    { Category: "Category 1", Subcategory: "Subcategory 1", Value1: "50", Value2: "30" },
    { Category: "Category 1", Subcategory: "Subcategory 2", Value1: "60", Value2: "40" },
    { Category: "Category 2", Subcategory: "Subcategory 1", Value1: "70", Value2: "50" },
    { Category: "Category 2", Subcategory: "Subcategory 2", Value1: "80", Value2: "60" }
]

Answer №1

If you want to achieve that functionality, you can utilize the combination of reduce and obtaining the Object.values from it:

var array = [ { Category: "Category 1", Item: "Item 1", Value1: "15", Value2: "5" }, { Category: "Category 1", Item: "Item 2", Value1: "20", Value2: "10" }, { Category: "Category 2", Item: "Item 1", Value1: "25", Value2: "15" }, { Category: "Category 2", Item: "Item 2", Value1: "30", Value2: "20" }, { Category: "Category 1", Item: "Item 1", Value1: "35", Value2: "25" }, { Category: "Category 1", Item: "Item 2", Value1: "40", Value2: "30" }, { Category: "Category 2", Item: "Item 1", Value1: "45", Value2: "35" }, { Category: "Category 2", Item: "Item 2", Value1: "50", Value2: "40" }];

var result = Object.values(array.reduce((acc, {Value1, Value2,...rest})=>{
    const key = Object.values(rest).join('|');
    acc[key] = acc[key] || {...rest, Value1:0,Value2:0};
    acc[key].Value1+=+Value1;
    acc[key].Value2+=+Value2;
    return acc;
},{}));

console.log(result);

Answer №2

const data = [{Phase:"Phase 1",Step:"Step 1",Value1:"15",Value2:"5"},{Phase:"Phase 1",Step:"Step 2",Value1:"20",Value2:"10"},{Phase:"Phase 2",Step:"Step 1",Value1:"25",Value2:"15"},{Phase:"Phase 2",Step:"Step 2",Value1:"30",Value2:"20"},{Phase:"Phase 1",Step:"Step 1",Value1:"35",Value2:"25"},{Phase:"Phase 1",Step:"Step 2",Value1:"40",Value2:"30"},{Phase:"Phase 2",Step:"Step 1",Value1:"45",Value2:"35"},{Phase:"Phase 2",Step:"Step 2",Value1:"50",Value2:"40"}]

const finalResult = data.reduce((result, d) => {
  let key = `${d.Phase}_${d.Step}`;
  result[key] = result[key] || {...d, Value1: 0, Value2: 0};
  result[key].Value1 += +d.Value1;
  result[key].Value2 += +d.Value2

  return result
}, {})

console.log(Object.values(finalResult))

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

Converting all numbers separated by commas to numbers separated by periods in a string using JavaScript

Imagine a scenario where you have a string containing numbers, such as, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text Your task is to replace the numbers with decimals instead of commas without altering anything else in the ...

Angular allows for a maximum time span of 60 days between two date inputs

I am looking to implement a validation in JavaScript or TypeScript for Angular where the start date cannot be more than 60 days after the end date is entered. The requirement is to enforce a "maximum range of 60 days" between the two input dates (dateFro ...

Tips for customizing the timing of a Bootstrap modal's opening delay?

I have integrated gem "bootstrap-sass", "~> 2.3.0.0", which indicates that I am utilizing Bootstrap 2. Detailed information on the modal can be found here. The code for my custom modal looks like this: #Modal.modal.hide.fade{"aria-hidden" => "true" ...

Determining the Nearest Form to an Element using jQuery

I developed a JavaScript/jQuery script that allows me to check all checkboxes within a form. The function works effectively, but the issue is that it checks all checkboxes on the page regardless of their form wrapper. Here is the function: function toggl ...

Animate jQuery Images - Transform and smoothly reveal element

Hey there! I've managed to create a color switcher that gives a sneak peek of different themes. Currently, it simply switches the image source and loads the new image. But I'm curious if it's possible to add a fadeIn effect to enhance the t ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Combining res.render and redirect in Express.js for efficient rendering and redirection

I am currently developing a web application that involves setting up routes for user authentication. The Challenge: After a successful registration, I want to redirect the user to /login page while also including render options. However, when I use render ...

Guide on loading xml information from a web browser using JavaScript

I have been working on loading data from the browser using a URL and currently utilizing JavaScript to achieve this. window.onload = function() { // This is the specific URL I am attempting to load data from. // The XML fi ...

JS custom scrollbar thumb size issues in relation to the scroll width of the element

I recently implemented a custom scrollbar for a component on my website. To determine the length of the scrollbar thumb, I use the formula viewportWidth / element.scrollWidth;. This provides me with a percentage value that I then apply to the thumb elemen ...

Error: Unable to access the 'length' property of an undefined value | Solving the challenge of finding the shortest word within a string | Codewars Problem

I'm currently working on a function to find the shortest word in a given string of words. Issue: I encountered the error below TypeError: Cannot read property 'length' of undefined at findShort at Test.describe._ at /runner/fra ...

Guide to including objects into your project without the need for babel through the use of CDN

I'm struggling with getting my Vue code to transpile properly due to some issues. I have resorted to loading Vue and other packages directly using CDN links, like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-vue/1.8.33/surv ...

Zurb Foundation's sections have a strange issue where navigating between them introduces unexpected whitespace

I'm feeling frustrated as I try to work with Zurb Foundation sections. I've updated to the latest version 4.3.1. Following the documentation provided here: but encountering strange behavior while navigating through results. Refer to the screen ...

Discovering the clicking actions on PDF elements within an HTML environment

I am currently working on developing a web application that involves rendering various pdf objects. My main goal is to be able to detect the position of a click inside the pdf container. However, it seems like the OnClick event is not functioning as expe ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Implement styling based on user input - Transmit form data via PHP to designated email address

My form allows people to provide their details and share their current timetable. I then group them based on suitable times The PHP form currently prints either 'work' or 'free' into a table cell, based on user selection in the form, a ...

"Troubleshooting: Angular ng-show not triggering correctly upon first loading of the

Utilizing Angular's ng-show directive to adjust the display of questions in a quiz and show a result upon completion, everything is functioning as intended except for the initial question. Upon loading the quiz, $scope.image is initialized as false. S ...

Utilizing helper functions in Node based on their specific types

In my helper module, I have different files like content, user, etc. These files define various helpers that can be used in the router. Below is the code for the router: router.js var helper = require("./helper"); function index(response) { response ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...