DEV Community

Discussion on: Help? .map .reduce

Collapse
 
ecyrbe profile image
ecyrbe • Edited

I gave a first wrong answer, as i didn't read your spec carrefully.
so here how to do it

const sum = (a, b) => a+b;
const uniqueCategories = (array) => [...new Set(array.map(item => item.category))];

const apiResult = [
  {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 chartData = uniqueCategories(apiResult).map(category => [
  category,
  apiResult
    .filter(item => item.category===category)
    .map(item => item.price)
    .reduce(sum)
]);
console.log(JSON.stringify(chartData));
Collapse
 
cristiantsantos profile image
cristiantsantos

Thank you very much, it helped me a lot, but the graph still doesn't work. =(

It works when I use:
const chartdata1 =[["Category","value"],["Categoria1", 16.6],["Categoria2", 16]]

the code returns the same thing, it's very strange:
[["Category","value"],["Categoria1",16.6],["Categoria2",16]]

*I used the splice to add the header
chartData.splice(0, 0, ["Category","value"])

Collapse
 
cristiantsantos profile image
cristiantsantos

returns: Table has no columns

Thread Thread
 
ecyrbe profile image
ecyrbe

you should post your code, so we can help.