Problem with .reduce() - functional programming

Hi,

Trying to work on my functional programming, I have the data below and i want to return a simple new object {totalAgeValue: x} where x is all the ages added together.

        const data = [{
            firstName: 'Jon',
            lastName: 'Jones',
            gender: 'male',
            age: 28,
            employed: true
        }, {
            firstName: 'Angie',
            lastName: 'Ball',
            gender: 'female',
            age: 30,
            employed: false
        }, {
            firstName: 'Lee',
            lastName: 'West',
            gender: 'male',
            age: 8,
            employed: false
        }, {
            firstName: 'Ray',
            lastName: 'Moore',
            gender: 'male',
            age: 74,
            employed: true
        }, {
            firstName: 'Rita',
            lastName: 'Smith',
            gender: 'femala',
            age: 54,
            employed: true
        }, {
            firstName: 'Gary',
            lastName: 'Neil',
            gender: 'male',
            age: 31,
            employed: true
        }]

The below is the closest I’ve come to doing this but its returning {totalAgeValue: "[object Object]31"} and I have no idea why. I have already checked the docs and they are not helping me. Whats confusing me is that simply returning acc += curr.age gives me the number I want, but as soon as I try and return it in an object it breaks. I know I can change the initial value to an object as well, but don’t know how I would work it out from there, or if that is even applicable here.

        const totalAge = data.reduce((acc, curr) => {
            return {
                totalAgeValue: acc += curr.age
            }
        }, 0);

I could probably do the below and it works, but thought they may be a better way of returning the object within the reduce function itself

        const totalAge = data.reduce((acc, curr) => {
            return acc += curr.age
        }, 0);

        let obj = {
            totalAgeValue: totalAge
        }

        console.log(obj);

Thanks for your help

Like you suspected it is the way you are setting and using the initial value , while your second solution works fine, you could do something like this to make it work with the reduce

       const totalAge = data.reduce((acc, curr) => {
              acc.totalAgeValue +=curr.age
              return acc
        }, {totalAgeValue: 0});

Perhaps the easiest way to comprehend what is happening inside the reduce callback is to use console.log(acc,curr) inside there

1 Like

Thanks for this, I knew I wasn’t too far off, but spent far too long racking my brain to work it out. Didn’t realise you could set a number as an initial value within the object itself. Thanks for the help.