如何在Javascript中找到对象数组中的属性的最小值和最大值

MaY*_*YaN 5 javascript jquery

我有以下javascript对象:

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

Person2.Name = "Joe";
Person2.Age = 5;
Run Code Online (Sandbox Code Playgroud)

然后我有一系列的人,如何根据人的年龄找到最小/最大?

Javascript或Jquery中的任何解决方案都是可以接受的.

非常感谢您的帮助.

Koo*_*Inc 17

假设您的数组如下所示:

var persons = [{Name:"John",Age:12},{Name:"Joe",Age:5}];
Run Code Online (Sandbox Code Playgroud)

然后你可以:

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;}))
Run Code Online (Sandbox Code Playgroud)

[ 编辑 ]添加ES2015方法:

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') 
);
Run Code Online (Sandbox Code Playgroud)