我正在尝试编写一个函数,将一个对象数组作为参数,如:function getOldest([{name:john, age:69}, {name:jane, age:28}, {name:paul, age: 19}])
该函数将检查对象的age属性并找到最大值,然后返回name属性。
getOldest([{name: john, age: 35}, {name: jane, age: 20}, {...}])
returns "john"
此外,如果两个键值对共享相同的值,就像两个人具有相同的年龄一样,它将返回一个数组。
getOldest([{name: john, age: 20}, {name: jane, age: 20}, {...}])
returns ['john', 'jane']
我一直试图弄清楚如何做这个约五个小时,但我无法理解。
使用sort
,然后使用filter
,最后使用map
var arr = [{name:"john", age:69}, {name:"jane", age:28}, {name:"paul", age: 19}];
arr.sort( ( a, b ) => b.age - b.age ); //sort by age in reverse
var maxAge = arr[ 0 ].age; //find max age
var output = arr.filter( a => a.age == maxAge ).map( a => a.name ); //returns array of max age name
演示
var arr = [{
name: "john",
age: 69
}, {
name: "jane",
age: 28
}, {
name: "paul",
age: 19
}];
arr.sort((a, b) => b.age - b.age); //sort by age in reverse
var maxAge = arr[0].age; //find max age
var output = arr.filter(a => a.age == maxAge).map(a => a.name); //returns array of max age name
console.log(output);
或者首先使用maxAge
找到map
var arr = [{name:"john", age:69}, {name:"jane", age:28}, {name:"paul", age: 19}];
var maxAge = Math.max.apply( null, arr.map( a => a.age ) );
var output = arr.filter( a => a.age == maxAge ).map( a => a.name ); //returns array of max age name
演示
var arr = [{name:"john", age:69}, {name:"jane", age:28}, {name:"paul", age: 19}];
var maxAge = Math.max.apply( null, arr.map( a => a.age ) );
var output = arr.filter( a => a.age == maxAge ).map( a => a.name ); //returns array of max age name
console.log( output );
我总是返回一个数组来保持一致性:
function getOldest(arr){
const old = arr.reduce((acc, {age}) => Math.max(acc, age), 0);
return arr.filter(({age}) => age === old);
}
首先,它使用reduce遍历数组并找到最老的年龄,然后返回由此过滤的数组。
如果你想一步减少:
function getOldest(arr){
var old = 0;
return arr.reduce((arr, {name, age}) => {
if(age > old){
old = age;
return [name];
}
if(age === old) return arr.concat(name);
return arr;
}, []);
}
由于已经有答案......在我看来减少就足够了。另外,我认为总是返回一个数组会更好。根据某些随机标准返回不同类型的函数不友好:
function getOldest(data) {
var max = -Infinity;
return data.reduce((acc, obj) => {
obj.age > max? (acc = [obj.name]) && (max = obj.age) :
obj.age == max? acc.push(obj.name): null;
return acc;
},[]);
}
var data = [{name: 'paul', age: 19},
{name: 'john', age: 69},
{name: 'jane', age: 28},
{name: 'fred', age: 13},
{name: 'tom' , age: 69}];
console.log(getOldest(data));
var myarray = [{name: 'john', age: 35}, {name: 'jane', age: 20}];
var oldest = getoldest(myarray);
alert(oldest.name);
在功能中你可以做这样的事情
function getoldest(myarray){
var oldest = Math.max.apply(Math,myarray.map(function(myarray){return myarray.age;}));
var obj = myarray.find(function(o){return o.age == oldest;});
return obj;
};
这样您就可以将返回的对象用于其他内容。
function getOldest(arr){
return arr.reduce( function(acc,current){
if (acc.age > current.age) {
return acc
} else { return current}
}).name
}
编辑:这实际上是这里最好的方法,只是减少,就是它,没有排序或过滤。