개발자를 위한 웹 기술 - Array.prototype.reduce() 을 정리한 글 입니다.
:reduce()
메서드는 배열의 각 요소에 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환한다.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce((previousValue, currentValue) => previousValue + currentValue, initialValue);
console.log(sumWithInitial);
// 10
reduce 함수는 네 개의 인자를 가진다.
reducer 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 된다.
arr.reduce(callback[, initialValue])
: 배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받는다.
accumulator
currentValue
currentIndex (optional)
array (optional)
콜백의 최초 호출 때, accumulator와 currentValue는 두 가지 값 중 하나를 가질 수 있다.
- initialValue를 제공하지 않으면, reduce()는 인덱스 1부터 시작해 콜백 함수를 실행하고 첫 번째 인덱스는 건너 뛴다.
- initialValue를 제공하면 인덱스 0에서 시작한다.