3

I need to write a code that will look through the data array, and return the name of the oldest person.

console.log('The oldest person is ${oldestPerson}.')

let data = {
    {
        name: Henry,
        age: 20,
        job: 'store clerk'
    },
    {
        name: Juliet,
        age: 18,
        job: 'student'
    },
    {
        name: Luna,
        age: 47,
        job: 'CEO'
    },

So far, I'm able to return separate arrays containing the names and ages, but I'm not sure how to find the oldest age and return name of the oldest person.

let names = data.map((person) => {
    return person.name
});

let ages = data.map((person) => {
    return Math.max(person.age)
});

1
  • 1
    sort the list and take the first one? Commented Feb 13, 2019 at 18:52

2 Answers 2

2

Using reduce

let data = [{
    name: ' Henry',
    age: 20,
    job: 'store clerk'
  },
  {
    name: 'Juliet',
    age: 18,
    job: 'student'
  },
  {
    name: 'Luna',
    age: 47,
    job: 'CEO'
  }
];
var max = 0;
console.log(data.reduce((acc, a) => {
  if (a.age > max) {
    acc = a.name
    max = a.age;
  }
  return acc;
}, ""))

Sign up to request clarification or add additional context in comments.

4 Comments

That logs the age, not the name :)
thanks mate for pointing that
Thank you both for the help! I'm new at this and wouldn't have thought to use .reduce. Reading up more on it now. Thanks again.
If it helped you upvote and mark it as correct so it can help others too
2

To get the max age, you've got no choice but to loop over the entire array (and get the oldest one). So while you're looping over the array, grab the name too.

This is one approach of many:

let highestAge = 0;
const oldestName = data.reduce((prev,curr) => {
  if(curr.age > highestAgo) {
    highestAge = curr.age;
    return curr.name;
  }
  return prev;
},'');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.