DEV Community

Discussion on: Help? .map .reduce

Collapse
 
ecyrbe profile image
ecyrbe

For those reading this in the future :

Budi answer is much faster to execute than the one i provided above.

My approach is using functionnal js, no mutated data. For small data tables, it's ok.

But using Budi aproach is much faster if your dataset is large.

Collapse
 
khuongduybui profile image
Duy K. Bui

we can do it purely functional too

const input = [
  {name: "test1", category: "Categoria1", price: 3},
  {name: "test2", category: "Categoria1", price: 13.6},
  {name: "test3", category: "Categoria2", price: 8},
  {name: "test4", category: "Categoria2", price: 8}
];
const map = input
  .map((item) => [item. category, item.price])
  .reduce((result, current) => {
    if (result[current[0]] === undefined) result[current[0]] = 0;
    result[current[0]] += result[current[1]];
    return result;
  }, {});
const output = Object.keys(result).map((key) => [key, result[key]])