DEV Community

Cover image for Using reduce to find the oldest age in an array
Marco Agas
Marco Agas

Posted on

Using reduce to find the oldest age in an array

In this post, I will explain how to find the oldest person in an array. Because it is an array, we can make use of the reduce method in order to return a single name, i.e. the oldest person.

The following was taken from The Odin Project JavaScript example for findTheOldest with help from iVuDang's method.

Step 0 - Create the Initial Array

Let's start with the array:

const people = [
    {
      name: "Carly",
      yearOfBirth: 1942,
      yearOfDeath: 1970,
    },
    {
      name: "Ray",
      yearOfBirth: 1962,
      yearOfDeath: 2011,
    },
    {
      name: "Jane",
      yearOfBirth: 1912,
      yearOfDeath: 1941,
    },
  ]
Enter fullscreen mode Exit fullscreen mode

Step 1 - Get Age Function

Next, we want to work out who is the oldest year. If someone didn't have a year of death, then we would like to return the current year.

We can start with a function to calculate the age of each person:

const getAge = function(birth, death) {
 if (!death) {
death = new Date().getFullYear(); // return current year using Date()
}
return death - birth; // else just return age using death minus birth
Enter fullscreen mode Exit fullscreen mode

Step 2 - Find The Oldest

Now we'd like to create a function in order to find the oldest person. We'll use reduce to return a single value, i.e. the person's name.

Reduce Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Find The Oldest Function

  const findTheOldest = function(array) { 
// Use reduce method to reduce the array by comparing current age with previous age
  return array.reduce((oldest, currentPerson) => {
    // oldestAge gets the age of the oldest person's year of death and birth
    const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);

    // currentAge gets the age of the current person's year of death and birth
    const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath);

    // return name if current age is older than the oldest age, else return current oldest age
    return oldestAge < currentAge ? currentPerson : oldest;
  });

};

console.log(findTheOldest(people).name); // Ray

Enter fullscreen mode Exit fullscreen mode

Conclusion

I'm still learning JavaScript day-by-day, but using reduce was quite tricky. I learnt that you don't need to use all the parameters for reduce if you don't need to, you can simply use the previous value and the current value.

Also, you can use something like an if statement to compare the current oldest to the new oldest age, and return the oldest one from there.

Hope you learnt something today, happy coding! πŸŽ‰

Here's my GitHub profile if you'd like to follow my journey πŸ—ΊοΈ

Photo by Naassom Azevedo on Unsplash

Top comments (0)