JSFiddle - React, Tailwind, and code Playground

by Dmitri Ganenco

JavaScript

const data = [{
  product: 'GL',
  channel: 'phone',
  total: 2
}, {
  product: 'GL',
  channel: 'ex',
  total: 5
}, {
  product: 'GL',
  channel: 'phone',
  total: 2
}, {
  product: 'AP',
  channel: 'phone',
  total: 2
}, {
  product: 'AP',
  channel: 'ex',
  total: 2
}, {
  product: 'zxc',
  channel: 'phone',
  total: 2
}, {
  product: 'foo',
  channel: 'sdf',
  total: 2
}, {
  product: 'GL',
  channel: 'internet',
  total: 2
}, {
  product: 'GL',
  channel: 'phone',
  total: 2
}, {
  product: 'bar',
  channel: 'phone',
  total: 2
}, ];

const reducer1 = data.reduce((acc, r) => {
  acc[r.product] = acc[r.product] || [];
  acc[r.product].push(r);
  return acc;
}, Object.create(null));

const a = Object.keys(reducer1).map(key => reducer1[key]).reduce((acc, r) => {
  r.forEach(item => {
    acc[item.channel] = acc[item.channel] || [];
    acc[item.channel] = Number.isNaN(acc[item.channel]) ? 0 : Number(acc[item.channel]) + Number(item.total);
  })
  return acc;
}, Object.create(null));

console.log(JSON.stringify(a));