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
Thank you,
where do I find stackoverflow?
Thanks again, but the code didn't work
You can find here stackoverflow.com For the code that didn't work above try here playcode
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.
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]])
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This kind of question is better placed in stackoverflow.
Thank you,
where do I find stackoverflow?
Thanks again, but the code didn't work
You can find here stackoverflow.com
For the code that didn't work above try here playcode
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.
we can do it purely functional too