const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue)
arr.reduce(callback[, initialValue])
callback 함수의 반환값을 누적한다initialValue를 제공한 경우에는 initialValue의 값입니다.callback함수 실행 시 accumulator 인수에 제공되는 값reduce()를 호출할 경우 에러가 발생한다accumulator는 배열의 첫 번째 값과 같고 currentValue는 두 번째와 같습니다.initailVaue가 없을때
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue) { return accumulator + currentValue; });
| callback | accumulator | currentValue | 반환 값 |
|---|---|---|---|
| 1번째 호출 | 0 | 1 | 1 |
| 2번째 호출 | 1 | 2 | 3 |
| 3번째 호출 | 3 | 3 | 6 |
| 4번째 호출 | 6 | 4 | 10 |
initailVaue가 있을때
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue) { return accumulator + currentValue; },0);
| callback | accumulator | currentValue | 반환 값 |
|---|---|---|---|
| 1번째 호출 | 0 | 0 | 0 |
| 2번째 호출 | 0 | 1 | 1 |
| 3번째 호출 | 1 | 2 | 3 |
| 4번째 호출 | 3 | 3 | 6 |
| 5번째 호출 | 6 | 4 | 10 |