0

I have an array:

const expenses = [
        { key: '1', sum: '100', category: 'car' },
        { key: '2', sum: '200', category: 'food'},
        { key: '3', sum: '300', category: 'furniture'},
        { key: '4', sum: '400', category: 'food'},
        { key: '5', sum: '700', category: 'car' },
    ]

How can I get new array or objects with total amount of certain categories? Like

newArray = [
{category: 'car' totalSum:800},
{category: 'food' totalSum:600},
{category: 'furniture' totalSum:300}
]

Thanks for any suggestions.

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Vova
  • 750
  • 11
  • 26

1 Answers1

2

Use Array.prototype.reduce():

const expenses = [{key:'1',sum:'100',category:'car'},{key:'2',sum:'200',category:'food'},{key:'3',sum:'300',category:'furniture'},{key:'4',sum:'400',category:'food'},{key:'5',sum:'700',category:'car'},],
    
      result = Object.values(expenses.reduce((r, {category, sum}) =>
        (r[category] = {category, totalSum: (r[category]?.totalSum || 0)+ +sum}, r), {}))
        
console.log(result)
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • Hi igen Yevgen. May I ask you to explain this code? The reason is I am trying to change 'category' value (for example, from 'food' to 'myFood') before return result. How can I do it? – Vova Jun 15 '20 at 14:07
  • @Vova : is it all `category` values you need to change or just some of them (based on some condition)? – Yevhen Horbunkov Jun 15 '20 at 14:11
  • it's not category) Instead of it I need to modify date. I have extra element in array: date: '8 June 2020', date: '5 June 2020'. I want to make total 'June 2020' – Vova Jun 15 '20 at 14:16
  • I have this code to make it. -> let dates = result.map(elem => elem.date.split(' ').slice(1).join(' ')); but don't know how to add it inside your code) – Vova Jun 15 '20 at 14:16
  • 1
    @Vova : would [that](https://codepen.io/ygorbunkov/pen/dyGpGMO?editors=0012) help? – Yevhen Horbunkov Jun 15 '20 at 14:26
  • yes, it works. Thanks again – Vova Jun 15 '20 at 14:43