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