如何从具有最高键值和名称的数组中返回对象 - JavaScript?

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/31 23:40:17

假设我们有一个对象数组,其中包含有关某些学生在测试中的分数的信息 −

const students = [
   { name: 'Andy', total: 40 },
   { name: 'Seric', total: 50 },
   { name: 'Stephen', total: 85 },
   { name: 'David', total: 30 },
   { name: 'Phil', total: 40 },
   { name: 'Eric', total: 82 },
   { name: 'Cameron', total: 30 },
   { name: 'Geoff', total: 30 }
];

我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组并返回一个对象,该对象包含总分最高的学生的姓名和总分。

因此,对于上述数组,输出应该是 −

{ name: 'Stephen', total: 85 } 

示例

以下是代码 −

const students = [
   { name: 'Andy', total: 40 },
   { name: 'Seric', total: 50 },
   { name: 'Stephen', total: 85 },
   { name: 'David', total: 30 },
   { name: 'Phil', total: 40 },
   { name: 'Eric', total: 82 },
   { name: 'Cameron', total: 30 },
   { name: 'Geoff', total: 30 }
];
const pickHighest = arr => {
   const res = {
      name: '',
      total: -Infinity
   };
   arr.forEach(el => {
      const { name, total } = el;
      if(total > res.total){
         res.name = name;
         res.total = total;
      };
   });
   return res;
};
console.log(pickHighest(students));

输出

这将在控制台上产生以下输出 −

{ name: 'Stephen', total: 85 }

相关文章


有用资源