Home > Net >  Sum Number values in array of objects and Keep Group Value
Sum Number values in array of objects and Keep Group Value

Time:09-22

var myArrayOfObjects = [{Group:MD,qtyA:4,qtyB:5},{Group:IL,qtyA:1,qtyB:3},{Group:FL,qtyA:5,qtyB:5}];

//RESULT I'M LOOKING FOR:
// [{Group:MD,Total:9},{Group:IL,Total:4},{Group:FL,Total:10}]

I'm initially using reduce to get the myArrayOfObjects but I can't figure out how to total everything and keep the Group in the object as part of the array

CodePudding user response:

You could do it with Array.map() and Array.reduce():

var myArrayOfObjects = [
  { Group: "MD", qtyA: 4, qtyB: 5 },
  { Group: "IL", qtyA: 1, qtyB: 3 },
  { Group: "FL", qtyA: 5, qtyB: 5 },
];
var result = myArrayOfObjects.map(({ Group, ...quantities }) => ({
  Group,
  Total: Object.values(quantities).reduce((a, b) => a   b, 0),
}));
console.log(result);

CodePudding user response:

This solution will sum up all numeric values within a group. You should use map() to get the result for each group and then use reduce() to calculate the total quantity.

const myArrayOfObjects = [
  { Group: "MD", qtyA: 4, qtyB: 5 },
  { Group: "IL", qtyA: 1, qtyB: 3 },
  { Group: "FL", qtyA: 5, qtyB: 5 },
];

const result = myArrayOfObjects.map((group) => ({
  Group: group.Group,
  Total: Object.values(group).reduce((total, quantity) =>
    typeof(quantity) === "number" ? (total  = quantity) : total, 0
  ),
}));

console.log(result)
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related