Search code examples
javascriptlodash

Group by data by key and return a new object containing the sum value of another key


I have data like that:

const data = [
  {name: 'alice', colors: ['red', 'blue'], count: 1, day: '2018-11-12'},
  {name: 'duke', colors: ['red', 'blue'], count: 1, day: '2018-12-12'},
  {name: 'bob', colors: ['blue'], count: 1, day: '2018-11-11'},
  {name: 'alice', colors: ['blue'], count: 1, day: '2018-11-10'},
  {name: 'carl', colors: ['blue'], count: 3, day: '2018-11-01'},
  {name: 'bob', colors: ['red'], count: 1, day: '2017-11-12'},
  {name: 'bob', colors: [], count: 1, day: '2018-11-12'},
  {name: 'bob', colors: ['red', 'blue', 'yellow'], count: 1, day: '2018-11-11'},
  {name: 'alice', colors: ['yellow'], count: 2, day: '2018-11-11'},
  {name: 'duke', colors: ['red', 'yellow'], count: 1, day: '2018-11-12'},
];

Now I want to group by data by day and get the sum of key count so obtain an array of objects like that:

const newData = [
  {day: '2018-11-12', countSum: 5}, // sum of {name: 'alice', colors: ['red', 'blue'], count: 1, day: '2018-11-12'}, {name: 'alice', colors: [blue'], count: 2, day: '2018-11-12'}, {name: 'bob', colors: [], count: 1, day: '2018-11-12'}, {name: 'duke', colors: ['red', 'yellow'], count: 1, day: '2018-11-12'}
  {day: '2018-12-12', countSum: 1},
  {day: '2018-11-11', countSum: 2}, // sum of {name: 'bob', colors: [blue'], count: 1, day: '2018-11-11'}, {name: 'bob', colors: ['red', 'blue', 'yellow'], count: 1, day: '2018-11-11'}
  {day: '2018-11-10', countSum: 1},
  {day: '2018-11-01', countSum: 3},
  {day: '2017-11-12', countSum: 1},
]

I tried to use groupBy of Lodash to group data by day but I can't to count the sum of count key. I need help.

Thanks a lot


Solution

  • Similar to "Reduce" solution by charlietfl, you can use for..of too.

    const data = [
      {name: 'alice', colors: ['red', 'blue'], count: 1, day: '2018-11-12'},
      {name: 'duke', colors: ['red', 'blue'], count: 1, day: '2018-12-12'},
      {name: 'bob', colors: ['blue'], count: 1, day: '2018-11-11'},
      {name: 'alice', colors: ['blue'], count: 1, day: '2018-11-10'},
      {name: 'carl', colors: ['blue'], count: 3, day: '2018-11-01'},
      {name: 'bob', colors: ['red'], count: 1, day: '2017-11-12'},
      {name: 'bob', colors: [], count: 1, day: '2018-11-12'},
      {name: 'bob', colors: ['red', 'blue', 'yellow'], count: 1, day: '2018-11-11'},
      {name: 'alice', colors: ['yellow'], count: 2, day: '2018-11-11'},
      {name: 'duke', colors: ['red', 'yellow'], count: 1, day: '2018-11-12'},
    ];
    
    let result = {}
    
    for(let d of data) {
      result[d.day] = result[d.day] || { day: d.day, countSum: 0}
      result[d.day].countSum += d['count']
    }
    
    console.log(Object.values(result))