Search code examples
javascriptarraysjavascript-objects

add up all value from array of objects's key after parseFloat()


so I have an array of objects inside like this:

        let ary = [
            {
                a : 'something',
                b: '2',
                c: 'something'
            },
            {
                a : 'something',
                b: '2',
                c: 'something'
            },
            {
                a : 'something',
                b: '2',
                c: 'something'
            }
        ]

I need to add up all key b's value on each object so I first change them to number with parseFloat like this:

ary.forEach( item => {
   item.b = parseFloat(item.b)
})

Next I use reduce() inside a .map function.

let total = ary.map((item, index) => {
    return ary.reduce((a, b) => ({x: a.b + b.b}))
})

but I did not get what I want, it return an array of objects with both same total value.

array = [
  {x : total},
  {x : total}
]

How should I get just single total value? like total = 2+2+2 and each 2 is from the b key in ary.


Solution

  • You can try with:

    const total = ary.reduce((sum, item) => (sum + parseFloat(item.b)), 0);
    

    With one loop you'll invoke parseFloat and summ all b properties.