我正在练习我的 javascript,我遇到了以下数组。
const people = [
{
name: 'Carly',
yearOfBirth: 2018,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941
},
]
我试图找到数组中最年长的人,但我一直找错人。这是我的代码 let findTheOldest = function(people) {
const oldest = people.sort((a,b) => (a.yearOfDeath - a.yearOfBirth) > (b.yearOfDeath - b.yearOfBirth) ? -1 : 1);
return oldest[0];
}
所以它一直说“卡莉”是最年长的人而不是“雷”?我该怎么办?请注意,“Carly”没有 yearOfDeath,因此她还活着。
最佳答案
您可以使用 reduce
,并为没有死亡日期的人使用当前年份:
const people = [{name:"Carly",yearOfBirth:2018},{name:"Ray",yearOfBirth:1962,yearOfDeath:2011},{name:"Jane",yearOfBirth:1912,yearOfDeath:1941}];
const findTheOldest = function(people) {
const thisYear = new Date().getFullYear();
return people.reduce((res, person) => {
const age = (person.yearOfDeath || thisYear) - person.yearOfBirth;
return age > res.age ? { person, age } : res;
}, { person: null, age: 0 }).person;
}
console.log(findTheOldest(people)); // Ray
关于javascript - 如何获取此数组中最年长的人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62785515/