javascript - 如何获取此数组中最年长的人

标签 javascript arrays

我正在练习我的 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/

相关文章:

javascript - 基于 Toggle 的隐藏元素 - Ratchet

c++ - 通过指针从c++中的函数返回数组,但是程序如何知道数组大小?

arrays - 我如何在 React CRUD 应用程序实现中处理数组

javascript - 调整输入字段 - 将总值放在 div 中

javascript - node.js:雅虎天气的 jQuery 插件不打印数据

javascript - 手动输入日期格式

java - 语法错误;分配数组时

javascript - 在 WebStorm 中镜像文字数组

c++ - 如何打印有序 C++ 字符串数组的直方图?

javascript - setTimeout 不延迟 $.each 中的函数调用