How to group by(multiple key) and sum of property values in javascript array (NodeJs)

74
July 26, 2021, at 9:50 PM

[ {Phase: "Phase 1", Step: "Step 1", Value1: "15"},{Phase: "Phase 1", Step: "Step 2", Value1: "20"},{Phase: "Phase 2", Step: "Step 1", Value1: "25"},{Phase: "Phase 2", Step: "Step 2", Value1: "30"},{Phase: "Phase 1", Step: "Step 1", Value1: "35"},{Phase: "Phase 1", Step: "Step 2", Value1: "40"},{Phase: "Phase 2", Step: "Step 1", Value1: "45"},Phase: "Phase 2", Step: "Step 2", Value1: "50"}]

[ {Phase: "Phase 1", Step: "Step 1", Value1: "50"},{Phase: "Phase 1", Step: "Step 2", Value1: "60"},{Phase: "Phase 2", Step: "Step 1", Value1: "70"},{Phase: "Phase 2", Step: "Step 2", Value1: "80"} ]

Answer 1

You can do this by using Map.

var arr = [ {Phase: "Phase 1", Step: "Step 1", Value1: "15"},{Phase: "Phase 1", Step: "Step 2", Value1: "20"},{Phase: "Phase 2", Step: "Step 1", Value1: "25"},{Phase: "Phase 2", Step: "Step 2", Value1: "30"},{Phase: "Phase 1", Step: "Step 1", Value1: "35"},{Phase: "Phase 1", Step: "Step 2", Value1: "40"},{Phase: "Phase 2", Step: "Step 1", Value1: "45"}, {Phase: "Phase 2", Step: "Step 2", Value1: "50"}];
    
    var groupByPhaseAndStep = new Map();
    
    for(const jObj of arr){
      const {Phase, Step, Value1='0'} = jObj;
      var key = Phase + '~~'+ Step;
      var val = eval(Value1);
      if(groupByPhaseAndStep.has(key)){
        val+=groupByPhaseAndStep.get(key);
      }
      groupByPhaseAndStep.set(key, val);
    }
    
    var outputArr = [];
    groupByPhaseAndStep.forEach(function(val, key){
      
      outputArr.push({
        Phase: key.split('~~')[0],
        Step: key.split('~~')[1],
        Value1: val
      });
    });
    
    console.log(outputArr);
READ ALSO
Having trouble deploying React app with a server on Heroku

Having trouble deploying React app with a server on Heroku

I am having trouble deploying on Heroku my React app and serverI have successfully Deployed on Heroku before but for some reason, I forgot how to properly do it

75
pymysql error message (INSERT INTO function)

pymysql error message (INSERT INTO function)

I encountered error message (INVALID SYNTAX) and have no idea why it happensPlease help to figure it out

91
How can I format a String number to have commas in Kotlin?

How can I format a String number to have commas in Kotlin?

i have this code to calculate distance from 2 points(lat,lon)

76
How do i select dropdown values which is outside from easyui datagrid table

How do i select dropdown values which is outside from easyui datagrid table

I'm working on the Codeigniter web application where I have used the jquery easyui Datagrid table, I have created the dropdown which is outside from the easyui Datagrid table, now how do I select dropdown value when Datagrid table is loaded?

59