javascript - How to sum values of objects and push it in an array -


i have array of objects dynamic , depend on selection of rows of table. example of it:

var obj = [             { name: "test1",  totalcosts: 45560, actualtotalcosts: 652112, riskcosts: 65442 },             { name: "test2",  totalcosts: 3434,  actualtotalcosts: 25252,   riskcosts: 34234 },             { name: "test3",  totalcosts: 23123, actualtotalcosts: 23242,  riskcosts: 0 },         ]; 

after array generated want call function pushes 1 more row in array , names "total" , sums respected values this:

{name: "total", totalcosts:72117, actualtotalcosts:700606 , riskscosts: 99676 }

obj[0].totalcosts + obj[1].totalcosts + obj[2].totalcosts = obj[3].totalcosts

i tried writing 1 limited knowledge, function instead of summing values 3 objects, summed entire object one.

            function sum1( obj ) {             var result1 = [];             (var = 0; < obj.length; i++) {                 var sum = 0, arr = [];                 (var key in obj[i]) {                     if (key != 'name') {                         sum += obj[i][key];                         arr.push(sum[key]);                     }                  }                 result1.push(arr);                 return result1;             }         } 

please provide function can sum objects , return array totals. tried using d3.sum not successful.

you can take functional approach aid of d3.sum...

  obj.push(d3.keys(obj[0])                //get keys obj[0]     .reduce(function(sumrow, sumcol) {    //construct summary row       var isnum = !isnan(obj[0][sumcol])  //only sum numeric fields       return (sumrow[sumcol] = (isnum ? d3.sum(obj, function(row) {         return row[sumcol]                //accessor column  d3.sum       }) : "all"), sumrow)                //append sum col sum row object     },{}));                               //initial value reduce {} 

working example

  (function() {      var obj = [{        name: "test1",        name2: "type1",        totalcosts: 45560,        actualtotalcosts: 652112,        riskcosts: 65442      }, {        name: "test2",        name2: "type2",        totalcosts: 3434,        actualtotalcosts: 25252,        riskcosts: 34234      }, {        name: "test3",        name2: "type3",        totalcosts: 23123,        actualtotalcosts: 23242,        riskcosts: 0      }];        obj.push(d3.keys(obj[0])        .reduce(function(sumrow, sumcol) {          var isnum = !isnan(obj[0][sumcol])          return (sumrow[sumcol] = (isnum ? d3.sum(obj, function(row) {            return row[sumcol]          }) : "all"), sumrow)        }, {}));        d3.select("#result").text(json.stringify(obj))    })()
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>  <div id="result"></div>


Comments