Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array group by multiple columns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading