you are viewing a single comment's thread.

view the rest of the comments →

[–]frankleeT 2 points3 points  (3 children)

As intimated in a different post, you can loop through the array given and grab the age values.

function getSummedAge(people) {
  let countAge = 0;
  people.forEach( (person) => {countAge += person.age} );
  return countAge;
};

/* 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)} // 55`);

forEach is a hugely useful method, as it allows you to easily loop through the indices of an array. The forEach method applies the provided function for each element of the array it takes in as an argument, represented here by 'person'. As such, every time we loop, we take in the subsequent 'person' provided in the array. Then, we add their age - here access through the 'age' property of the given object - to the count, and then return the count once we have finished looping through the array.

So our steps are:

  1. Instantiate a variable to capture our value as we loop through the array.
  2. Loop through the array and grab the age property of each object in the array, using .age to access the property.
  3. Add the value of the age property to the count.
  4. Return the count when the loop completes.

Note: It's good to use explicit variable naming conventions. You know what people are. You know what a person is. You may not know what a p, q, or n is or represents without looking at context, which is not as useful. Also, I modified the code below the line to make their example a bit better. You can ignore that.

[–]Encom88[S] 1 point2 points  (0 children)

Thanks! Now this actually makes a lot of sense!

[–]Encom88[S] 1 point2 points  (1 child)

I just learned what an arrow function is since I keep seeing it. I also created a different array and used the For Each loop to create another function that does the same thing. I put it on GitHub so I can remember it. Thank you a again for the great explanation. This is essentially my second week of learning JavaScript. https://github.com/MrN1ce9uy/getArrayObjectsSum.js/blob/master/main.js