使用Javascript查找具有最低关键值的对象 [英] Finding object with lowest value for some key, in Javascript
问题描述
在我的Javascript程序中,我有一个Person
对象的列表.
In my Javascript program, I have a list of Person
objects.
例如
[
"Michael": {
"age": 45,
"position": "manager",
...
},
"Dwight": {
"age": 36,
"position": "assistant manager",
...
},
....
]
我想找到最小的Person
.
我通过创建两个数组来实现此目的:创建所有Person
中的一个,并创建其所有年龄中的一个,并获取最低年龄的索引并将其应用于第一个数组.喜欢:
I've accomplished this by creating two arrays: one of all the Person
s 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?
推荐答案
您可以按age属性对person数组进行排序,然后选择第一个:
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]);
这篇关于使用Javascript查找具有最低关键值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!