DEV Community

Discussion on: Help? .map .reduce

Collapse
 
iambudi profile image
I am Budi • Edited

This kind of question is better placed in stackoverflow.

var data = [
  { 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 },
];

var result = {};
data.forEach(item => {
  const cat = item.category;
  if (result[cat] == undefined) {
    result[cat] = 0;
  }
  result[cat] += item.price;
});

console.log(Object.entries(result));
// output: [['Categoria1', 16.6],['Categoria2', 16]]
// simpler without map reduce
Collapse
 
cristiantsantos profile image
cristiantsantos

Thank you,

where do I find stackoverflow?

Thanks again, but the code didn't work

Collapse
 
iambudi profile image
I am Budi

You can find here stackoverflow.com
For the code that didn't work above try here playcode

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]])