9

I have the following javascript object:

Person1.Name = "John";
Person1.Age = 12;

Person2.Name = "Joe";
Person2.Age = 5;

I then have an array of persons, how do I find the Min/Max based on a persons age?

Any solution in Javascript or Jquery is acceptable.

your help is much appreciated.

4

2 Answers 2

24

Say your array looks like this:

var persons = [{Name:"John",Age:12},{Name:"Joe",Age:5}];

then you can:

var min = Math.min.apply(null, persons.map(function(a){return a.Age;}))
   ,max = Math.max.apply(null, persons.map(function(a){return a.Age;}))

[Edit] Added ES2015 method:

const minmax = (someArrayOfObjects, someKey) => {
  const values = someArrayOfObjects.map( value => value[someKey] );
  return {
      min: Math.min.apply(null, values), 
      max: Math.max.apply(null, values)
    };
};

console.log(
  minmax( 
    [ {Name: "John", Age: 12},
      {Name: "Joe", Age: 5},
      {Name: "Mary", Age: 3},
      {Name: "James sr", Age: 93},
      {Name: "Anne", Age: 33} ], 
    'Age') 
);

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

Comments

1

First you sort the array with a custom sorting function:

var sorted = persons.sort(function(a, b) {
  if(a.Age > b.Age) return 1;
  else if(a.Age < b.Age) return -1;
  else return 0;
});

Then you can just take the first and last:

var min = sorted[0],
    max = sorted[sorted.length - 1];

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.