Niko Gamulin
Niko Gamulin

Reputation: 66565

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 - Snack...), I would like to make two different sums:

The object array example is the following:

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}]

Does anyone know what is the most efficient way to sum the values for a given key (name) or multiple keys (mealNumber, name)?

Upvotes: 0

Views: 58

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

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 parameter

document.getElementById("result").textContent = JSON.stringify(dayTotals);
<div id="result"></div>

Upvotes: 1

Related Questions