我有以下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)
| 归档时间: |
|
| 查看次数: |
5607 次 |
| 最近记录: |