1

Below is the array that is generated from my json response

 [
        {
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30",
    "c4": "40"
        },
    {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25",
    "c4": "38"
        }
    ]

I need to calculate the sum of the values of the fields except the first field, as the first that I get is a field name

Result array:

  [
    "c1": 30,
    "c2": 60,
    "c3": 55,
    "c4": 78
      ]
indra257
  • 66
  • 3
  • 24
  • 50
  • 1
    Possible duplicate of [Better way to sum a property value in an array (Using Angularjs)](http://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array-using-angularjs) – Heretic Monkey May 09 '17 at 21:38

5 Answers5

1

Using only ES6, you can do this with 2 Array#reduce loops:

const data = [{"id":"name1","c1":"10","c2":"20","c3":"30","c4":"40"},{"id":"name2","c1":"20","c2":"40","c3":"25","c4":"38"}];

const result = data.reduce((sums, obj) => Object.keys(obj).reduce((s, k) => {    
    k === 'id' || (s[k] = (s[k] || 0) + +obj[k]);
    
    return s;
}, sums), {});

console.log(result);

Or you can use lodash's _.mergeWith(), and _.omit() the 'id' from the result:

const data = [{"id":"name1","c1":"10","c2":"20","c3":"30","c4":"40"},{"id":"name2","c1":"20","c2":"40","c3":"25","c4":"38"}];

const result = _.omit(_.mergeWith({}, ...data, (objValue = 0, srcValue = 0) => +objValue + +srcValue), 'id');

console.log(result);

 console.log(_.map(result, (v, k) => ({ [k]: v }))); // or as a series of objects
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Is there a way to change the output to the below format [ {"c1": 30}, {"c2": 60}, { "c3": 55}, {"c4": 78} ] – indra257 May 11 '17 at 14:57
  • You can use lodash's `_.map()` on the result -> `_.map(result, (v, k) => ({ [k]: v }));`. I've added an example to the 2nd answer. – Ori Drori May 11 '17 at 17:27
0

ES6 syntax:

const a =  [
        {
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30",
    "c4": "40"
        },
    {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25",
    "c4": "38"
        }
    ];

const b = a.reduce((a, v) => {
  Object.keys(v).filter(e => e.startsWith('c')).forEach(k => a[k] = (a[k]) ? a[k] + +v[k] : +v[k]);
  return a;  
}, {});
   
console.log(b)
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
0
var values = [{
        "id": "name1",
        "c1": "10",
        "c2": "20",
        "c3": "30",
        "c4": "40"
    },
    {
        "id": "name2",
        "c1": "20",
        "c2": "40",
        "c3": "25",
        "c4": "38"
    }
];

var results = {
    "id": "totals",
    "c1": 0,
    "c2": 0,
    "c3": 0,
    "c4": 0
}

values.forEach(function(item) {
    results.c1 += Number(item.c1);
    results.c2 += Number(item.c2);
    results.c3 += Number(item.c3);
    results.c4 += Number(item.c4);
});

console.log(JSON.stringify(results));
Chris Rouffer
  • 743
  • 5
  • 14
0

Assuming you are looking for a resulting object, and not an array of objects:

var srcObj = [{
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30",
    "c4": "40"
  },
  {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25",
    "c4": "38"
  }
];

var destObj = {};
srcObj.map((itm) => {
  Object.keys(itm).forEach(function (key) {
    if(key == 'id'){return;}
    if(!destObj[key]){
      destObj[key] = 0;
    }
    destObj[key] += parseInt(itm[key]);
  });
});

console.log(destObj);
Sasang
  • 1,261
  • 9
  • 10
0

Using lodash try

sum

_.sum([4, 2, 8, 6]);
// => 20

sumby

var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];

_.sumBy(objects, function(o) { return o.n; });
// => 20

// The `_.property` iteratee shorthand.
_.sumBy(objects, 'n');
// => 20
Abilash Arjunan
  • 323
  • 3
  • 11