Array group by multiple columns

Advertisements

i have this array

i want to store it on new array groupped by date and shift with new column totale of shifts per date

const arr = [
       { sum: 77, shift:  1, date: "2020-07-05T00:00:00" },

       { sum: 25, shift:  2, date: "2020-07-05T00:00:00" },

       { sum: 10, shift:  3, date: "2020-07-05T00:00:00" },

       { sum: 13, shift:  1, date: "2020-07-06T00:00:00" },

       { sum: 66, shift:  2, date: "2020-07-06T00:00:00" },

       { sum: 30, shift:  3, date: "2020-07-06T00:00:00" },

       { sum: 50, shift:  1, date: "2020-07-07T00:00:00" },

       { sum: 40, shift:  2, date: "2020-07-07T00:00:00" },

       { sum: 65, shift:  3, date: "2020-07-07T00:00:00" },
     ];

i already calculed totals but i dont know how to groupe by date and shift

i want an output like this

date shift 1 shift 2 shift 3 totale
07-05-2020 77 25 10 112
07-06-2020 13 66 30 109
07-07-2020 50 40 65 155

i tried this but not returning the correct values

const grouped = arr.reduce((acc, { sum, shift, date }) => {
  let dateKey = date.slice(0,10); 
  acc[dateKey] = acc[dateKey] || {};
  acc[dateKey][shift] = sum;
  return acc;
}, {})

>Solution :

You just need to calculate the total with the same logic.

Working Fiddle

const arr = [
  { sum: 77, shift: 1, date: "2020-07-05T00:00:00" },
  { sum: 25, shift: 2, date: "2020-07-05T00:00:00" },
  { sum: 10, shift: 3, date: "2020-07-05T00:00:00" },
  { sum: 13, shift: 1, date: "2020-07-06T00:00:00" },
  { sum: 66, shift: 2, date: "2020-07-06T00:00:00" },
  { sum: 30, shift: 3, date: "2020-07-06T00:00:00" },
  { sum: 50, shift: 1, date: "2020-07-07T00:00:00" },
  { sum: 40, shift: 2, date: "2020-07-07T00:00:00" },
  { sum: 65, shift: 3, date: "2020-07-07T00:00:00" },
];
const grouped = arr.reduce((acc, { sum, shift, date }) => {
  let dateKey = date.slice(0, 10);
  acc[dateKey] = acc[dateKey] || {};
  acc[dateKey][`Shift${shift}`] = sum;
  acc[dateKey].total = (acc[dateKey].total || 0) + sum;
  return acc;
}, {});
console.log(grouped);

Leave a ReplyCancel reply