이론으로 보는 Reduce( )
- 배열 안에 있는 모든 요소들을 이용해서 하나의 값으로 만들떄 이용함
- 모든 요소들을 더해서 하나의 값으로 만들 수 도 있고 (ex. [1,2,3,4] -> 10)
- 배열의 모든 요소를 쭉 스캔해서 가장 작은 값을 추출할 수 도 있다. (ex. [10,4,2,8] -> 2)
코드로 보는 배열의 모든 요소를 더하는 Reduce( )
# numbers 배열
const numbers = [1, 2, 3, 4];
# forEach
let total = 0;
numbers.forEach(number => { // total = Reduce의 인자 중 accumulator 와 같다.
total = total + number; // number = Reduce의 인자 중 currentValue 와 같다.
})
console.log(total); // total = 10
# reduce
const total = numbers.reduce((accumulator, currentValue) => { // currentValue : 현재 처리중인 요소를 나타냄
return accumulator + currentValue // accumulator : 현재 까지 누적된 값을 나타냄
}, 0); // 0 = accumulator 의 초기값
표로 보는 배열의 모든 요소를 더하는 Reduce( )

코드로 보는 가장 작은 값을 추출하는 Reduce( )
const numbers = [10, 4, 2, 8];
const smallest = numbers.reduce((accumulator, currentValue) =>
if(accumulator > currentValue) {
return currentValue;
}
return accumulator;
{);
console.log(smallest);
표로 보는보는 가장 작은 값을 추출하는 Reduce( )
