0

In my Javascript program, I have a list of Person objects.

For example

[
     "Michael": {
          "age": 45,
          "position": "manager",
          ...
     },
    "Dwight": {
          "age": 36,
          "position": "assistant manager",
          ...
     },
    ....
]

I want to find the youngest Person.

I've accomplished this by creating two arrays: one of all the Persons and one of all their ages, and getting the index of the lowest age and applying it to the first array. Like:

var arrayOfPersons = [persons[0], persons[1], ....];
var arrayOfAges = [persons[0].age, persons[1].age, ....];
var min = arrayOfAges.indexOf(Math.max.apply(Math, arrayOfAges));
var youngestPerson = arrayOfPerson[min];

The problem with this is it is inefficient doesn't seem like the best way. Also it doesn't deal with the fact that there may be a tie for youngest.

Does anyone know of a more native, simpler way to do this?

4
  • Your list seems wrong. Is it meant to be an array of objects or single object with person names as a keys? Commented Oct 30, 2014 at 12:02
  • arrayOfAges should be array of values not objects Commented Oct 30, 2014 at 12:04
  • @Heikki It's meant to be a list of Person objects Commented Oct 30, 2014 at 12:43
  • @theinvisible It is. It's a list of age values Commented Oct 30, 2014 at 12:43

1 Answer 1

0

You can sort the persons array by age property and pick first one:

var persons = [
    { name: 'Michael', age: 45, position: 'manager' },
    { name: 'Dwight', age: 36, position: 'assistant manager' },
    { name: 'Foo', age: 99, position: 'foo' },
    { name: 'Bar', age: 37, position: 'bar' }
];

persons.sort(function(a, b) {
    return a.age > b.age;
});

console.log('Youngest person: ', persons[0]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.