Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

자바스크립트 배열에서 상하류 순 속도(Net Velocity)를 계산하는 방법

문제 소개

모터보트가 상류(upstream)와 하류(downstream)를 오갈 때 기록된 속도 정보가 담긴 배열이 있다고 가정해 보겠습니다. 각 요소는 이동 방향과 그때의 속도를 객체 형태로 저장하고 있습니다.

다음은 예제로 사용할 샘플 배열입니다.

const arr = [{
    direction: 'upstream',
    velocity: 45
}, {
    direction: 'downstream',
    velocity: 15
}, {
    direction: 'downstream',
    velocity: 50
}, {
    direction: 'upstream',
    velocity: 35
}, {
    direction: 'downstream',
    velocity: 25
}, {
    direction: 'upstream',
    velocity: 40
}, {
    direction: 'upstream',
    velocity: 37.5
}];

풀이 접근

우리가 작성해야 할 함수는 이런 형태의 배열을 입력받아, 배가 전체 항해 과정에서 얻는 순 속도(net velocity), 즉 상류에서의 속도 합계에서 하류에서의 속도 합계를 뺀 값을 반환하는 함수입니다.

이 문제는 Array.prototype.reduce() 메서드를 활용하면 간결하게 해결할 수 있습니다. 배열을 한 번만 순회하면서 방향에 따라 값을 더하거나 빼면 되기 때문입니다.

그럼 findNetVelocity() 함수를 작성해 객체들을 순회하며 순 속도를 계산해 보겠습니다. 전체 코드는 다음과 같습니다.

예제 코드

const arr = [{
    direction: 'upstream',
    velocity: 45
}, {
    direction: 'downstream',
    velocity: 15
}, {
    direction: 'downstream',
    velocity: 50
}, {
    direction: 'upstream',
    velocity: 35
}, {
    direction: 'downstream',
    velocity: 25
}, {
    direction: 'upstream',
    velocity: 40
}, {
    direction: 'upstream',
    velocity: 37.5
}];
const findNetVelocity = (arr) => {
    const netVelocity = arr.reduce((acc, val) => {
        const { direction, velocity } = val;
        if(direction === 'upstream'){
            return acc + velocity;
        }else{
            return acc - velocity;
        };
    }, 0);
    return netVelocity;
};
console.log(findNetVelocity(arr));

코드 설명

reduce() 메서드는 초기값 0부터 시작해 배열의 각 객체를 순서대로 처리합니다. 각 단계에서 객체의 directionvelocity를 구조 분해 할당으로 꺼낸 뒤, 방향이 'upstream'이면 누적값에 속도를 더하고, 그렇지 않으면 속도를 뺍니다. 모든 요소를 처리한 후 최종 누적값이 곧 순 속도가 됩니다.

출력 결과

콘솔에 출력되는 결과는 다음과 같습니다.

67.5