2020-05-25

JavaScript - Aggregate numeric value of an array of objects

// Original array of objects
var objects_array = [
  { id_key: "a", numeric_value: 1 }, 
  { id_key: "b", numeric_value: 2 }, 
  { id_key: "c", numeric_value: 2 }, 
  { id_key: "a", numeric_value: 4 }
];

// Resulting array of objects
var objects_array_aggregated = [];

// Reduction function
objects_array.reduce(function(res, value) {
  if (!res[value.id_key]) {
    res[value.id_key] = { 
        id_key: value.id_key, 
        numeric_value: 0 
      };
    objects_array_aggregated.push(
      res[value.id_key]
    );
  }
  res[value.id_key].numeric_value += value.numeric_value;
  return res;
}, {});

// View the result
console.log(objects_array_aggregated)


Credits:
https://stackoverflow.com/questions/29364262/how-to-group-by-and-sum-array-of-object

No comments:

Post a Comment