Sum and group an array of objects

I have simple array of products category with quantity and price
I would simple return an array as
Rings - 3 (sum of qty) - $75 (sum of qty* price)
Bracelets - 3(sum of qty)- $90 (sum of qty* price)
The property .valore not exists but how can create to push a sum?
im tryin to do so with no success

let data = [
  { famiglia: 'Rings', qty: 10, price: 2 },
  { famiglia: 'Rings', qty: 10, price: 2 },  
  { famiglia: 'Rings', qty: 5 , price: 8},
  { famiglia: 'Bracelet', qty: 4 , price: 10},
  { famiglia: 'Bracelet', qty: 5 , price: 10}
];
let sumsArray = data.reduce(function(acc, curr) {
  let findIndex = acc.findIndex(item => item.famiglia === curr.famiglia);
  acc.valore=0;
  if (findIndex === -1) {
    acc.push(curr);
  } else {
   acc[findIndex].qty += curr.qty;
   acc[findIndex].valore += curr.qty * curr.price; //Here cant sum
  }
  return acc;
}, []);

The result i want is similar to
Select Category, Sum(qty) QtySum, Sum(qty*price) ValueSum
FROM Products
Group by Category

I not understand well reduce
some one can help?

Hi

You could maybe use reduce but I find it easier to use forEach and then store it as an object for fast access to different famiglia. If you want it as list at the end you can use Object.values(sumsArray)

let data = [
  { famiglia: 'Rings', qty: 10, price: 2 },
  { famiglia: 'Rings', qty: 10, price: 2 },  
  { famiglia: 'Rings', qty: 5 , price: 8},
  { famiglia: 'Bracelet', qty: 4 , price: 10},
  { famiglia: 'Bracelet', qty: 5 , price: 10}
];
let sumsArray = {}
data.forEach(item => {
  sums = sumsArray[item.famiglia]
  if (sums) {
    sums.qty += item.qty
    sums.valore += item.qty * item.price
  } else {
    sumsArray[item.famiglia] = {
      famiglia: item.famiglia,
      qty: item.qty,
      valore: item.qty * item.price
    }
  }
})
console.log(sumsArray)

tks it works fine (you forgot to declare sums)
Anyway i not understand how that code works: if sums is not undefined is calculate sums otherwise it create object with properties .famiglia .qty .valore
I understand?

tks again
have nice day

Hi. Yes you are correct. If sums exist it just adds to it and if don’t exist ( sums is undefined) the program creates a new one

Tks again
Happy coding

1 Like