Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

이름과 함께 가장 높은 키 값을 가진 배열에서 객체를 반환하는 방법 - JavaScript?

<시간/>

테스트에서 일부 학생의 점수에 대한 정보를 포함하는 객체 배열이 있다고 가정합니다.

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 }
];

우리는 그러한 배열 중 하나를 취하여 total 값이 가장 높은 학생의 이름과 합계가 있는 객체를 반환하는 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 }