Skip to content Skip to sidebar Skip to footer

How To Group Array Elements By Arbitrary Set Of Keys?

Having an array of objects I would like to sum the values by combining different set of keys. To be more specific, having an array of objects, describing the meal (0 - Breakfast, 1

Solution 1:

You need to use Array.prototype.reduce (no need of third-party libraries).

Run the following code snippet for a detailed sample:

var arrayIngredients = [{
  mealNumber: 4,
  name: "Sugars, total",
  quantity: 1.4300000000000002
}, {
  mealNumber: 4,
  name: "Magnesium, Mg",
  quantity: 14.950000000000001
}, {
  mealNumber: 3,
  name: "Vitamin A, IU",
  quantity: 27.9
}];

var dayTotals = arrayIngredients.reduce(function(result, next) {
  if (!result.hasOwnProperty(next.name))
    result[next.name] = {
      totalQuantity: 0
    };

  result[next.name].totalQuantity += next.quantity;

  return result;
}, {}); // this empty object is injected as "result" argument // in the Array.prototype.reduce callback #1 parameterdocument.getElementById("result").textContent = JSON.stringify(dayTotals);
<divid="result"></div>

Post a Comment for "How To Group Array Elements By Arbitrary Set Of Keys?"