0
help
ayormeday (7)

how do i modify the function to return the total summed age of all of the people.

function getSummedAge(people) {

const arrSum = arr => arr.reduce((name,age) => name + age, 0)
}

/ Do not modify code below this line /

const examplePeopleArray = [
{ name: 'John', age: 10 },
{ name: 'Jack', age: 20 },
{ name: 'Jane', age: 25 }
];

console.log(getSummedAge(examplePeopleArray), '<-- should be 55');

You are viewing a single comment. View All
2
heyitsmarcus (280)

This is a bit of a tricky one, but be sure to make sure you get a good grasp on how reduce works. The parameters you passed in do not correlate to the array in the manner that you think they do. name in your code is the accumulator of the reduce method and age represents the current value in the array.

The accumulator is some variable that is a sum of all of the previous iterations. In other words, if you had an array of [1,2,3] and I write this:

const arr = [1,2,3]
console.log(arr.reduce((accumulator, val) => accumulator + val), '<-- Will be 6')

You can see that it was just 1 + 2 + 3. The accumulator stores the total of what was added last time and then adds to that. And val was just the value at each point in the array. It's like running this for loop:

let total = 0;
for (let i = 0; i < arr.length; i++) {
	total += arr[i];
}
console.log(total, '<-- Will be 6')

You can use other types with this to get different results, but just focus on numbers at this point.

In other words, it's helpful to rename these to something that better fit what they do:

function getSummedAge(people) {

	const arrSum = people.reduce((accumulator,val) => { 
    	       //HINT 1: in here, see if accumulator has a property of age
               //HINT 2: the val parameter will always have an age attribute **in this example** because the way the array is defined
               //HINT 3: you'll want to return only ages that are added together, ignore the name property
	})

	return arrSum
}

/ Do not modify code below this line /

const examplePeopleArray = [
{ name: 'John', age: 10 },
{ name: 'Jack', age: 20 },
{ name: 'Jane', age: 25 }
];

console.log(getSummedAge(examplePeopleArray), '<-- should be 55');

Good luck!

1
mwilki7 (130)

@heyitsmarcus I always hated functional programming.
F# was a bad time in my life.

1
heyitsmarcus (280)

@mwilki7 It is one of my favorite things! haha To each their own, though. =]

1
ash15khng (220)

@heyitsmarcus It's satisfying when you can do relatively complicated stuff in one or two lines with functional programming.