티스토리 뷰

 

길이가 같은 두 정수 배열의 내적을 구해야한다.

먼저, 각 요소를 곱하고, 그 결과를 더해주어야 한다.

 

function solution(a, b) {
    let sum = 0;

    for (let i = 0; i < a.length; i++) {
        sum += a[i] * b[i];
    }

    return sum;
}

 

반복문이 나오면 배열이라면 map으로,

그 외라면 보통 reduce로 해결할 수 있다.

 

해당 코드는 이런 식으로 해결할 수 있다고 한다.

(acc, _, i) => acc += a[i] * b[i], 0

 

그런데 인자를 세 개나 사용하니 코드 해석이 어려워서,

reduce 문서를 확인했다.

 

Array.prototype.reduce() - JavaScript | MDN

The reduce() method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across al

developer.mozilla.org

 

(accumulator, currentValue, currentIndex, array)

 

이 경우, reduce 메서드는 배열의 각 요소를 순회해 누적 작업을 수행하는데

a와 b 배열의 동일 인덱스의 값을 곱하기 때문에 curr는 필요하지 않다.

댓글