2012-08-16 19 views
4

我有以下的JavaScript对象:你怎么找到最小和财产的最大的对象的数组,在Javascript

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

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

我再有人员组成的阵列,如何找到最小/最大基于一个人的年龄?

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

非常感谢您的帮助。

+0

[?你尝试过什么(http://whathaveyoutried.com) – 2012-08-16 10:23:00

+0

的[jQuery的最小可能重复/从数组元素的最大属性](http://stackoverflow.com/questions/5052673/jquery-min-max-property-from-array-of-elements) – 2012-08-16 10:23:26

+0

可能的重复[比较JavaScript的对象数组以获取最小/马克斯(http://stackoverflow.com/questions/8864430/compar e-javascript-array-of-objects-to-get-min-max) – 2012-08-16 10:23:43

回答

16

说你的阵列是这样的:

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

那么你可以:

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

[编辑]增加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') 
 
);

1

首先你整理了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; 
}); 

然后,你可以只取第一个和最后:

var min = sorted[0], 
    max = sorted[sorted.length - 1]; 
相关问题