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 }

해결 방법

이 문제는 forEach() 메서드를 사용하여 배열을 순회하면서 지금까지 확인한 최댓값보다 더 큰 total 값이 나타날 때마다 결과 객체를 갱신하는 방식으로 해결할 수 있습니다.

초기값으로 total-Infinity(음의 무한대)로 설정하면 어떤 점수와도 비교가 가능하기 때문에 안전하게 최댓값을 추적할 수 있습니다.

예제 코드

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));

코드 설명

  • 결과를 저장할 객체 res를 선언하고, total의 초기값을 -Infinity로 설정합니다.
  • forEach()로 배열의 모든 요소를 순회하면서 구조 분해 할당으로 nametotal을 추출합니다.
  • 현재 요소의 total이 기존 최댓값보다 크면 결과 객체의 nametotal을 갱신합니다.
  • 순회가 끝나면 최종 결과 객체를 반환합니다.

출력 결과

위 코드를 실행하면 콘솔에 다음과 같은 출력이 표시됩니다.

{ name: 'Stephen', total: 85 }

참고로, 동일한 로직은 reduce() 메서드를 활용해 한 줄로도 구현할 수 있습니다.

const pickHighest = arr => arr.reduce((max, el) => el.total > max.total ? el : max);

두 방법 모두 시간 복잡도는 O(n)으로, 배열의 길이에 비례하는 성능을 보입니다.