Search code examples
javascripthtmlreactjsarraysobject

groupe Array 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: 05, shift:  2, date: "2020-07-05T00:00:00" },

       { sum: 15, 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" },
     ];

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 45 10 132
07-06-2020 13 66 30 109
07-07-2020 50 40 90

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${shift}`] = sum;
  acc[dateKey].total = (acc[dateKey].total || 0) + sum;
  return acc;
}, {});

Solution

  • I think this function is what you need.

    const computeArray = (arr) => {
      const result = {}
      arr.forEach(item => {
        const field = `shift${item.shift}`
        if(!result[item.date]) {
          result[item.date] = {}
        }
        result[item.date][field] = (result[item.date][field] || 0) + item.sum
        result[item.date].total = (result[item.date].total || 0) + item.sum
      })
    
      return Object.keys(result).map(key => ({
        date: key,
        ...result[key]
        
      }))
    }