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)
});

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
lebookworm
  • 41
  • 3

2 Answers2

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;
},'');
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
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;
}, ""))
ellipsis
  • 12,049
  • 2
  • 17
  • 33