reduce 메서드는 자신을 호출한 배열을 모든 요소를 순회하며
인수로 전달받은 콜백 함수를 반복 호출한다.
콜백 함수의 반환값을 다음 순회 시에 콜백 함수의 첫 번째 인수로 전달 하면서 콜백 함수를 호출하여 하나의 결과 값을 만들어 반환한다.
첫번째 인수로 콜백 함수, 두 번째 인수로 초기값을 전달 받는다.
// 1부터 4까지 누적을 구한다.
const sum = [1, 2, 3, 4].reduce(
(accumulator, currentValue, index, array) => accumulator + currentValue,
0
);
console.log(sum); // 10
구분 | 콜백 함수에 전달되는 인수 | 콜백 함수의 반환값 | |||
accumulator | currentValue | index | array | ||
첫번째 순회 | 0(초기값) | 1 | 0 | [1,2,3,4] | 1(accumulator + currentValue) |
두번째 순회 | 1 | 2 | 1 | [1,2,3,4] | 3(accumulator + currentValue) |
세번째 순회 | 3 | 3 | 2 | [1,2,3,4] | 6(accumulator + currentValue) |
네번째 순회 | 6 | 4 | 3 | [1,2,3,4] | 10(accumulator + currentValue) |
// 평균 구하기
const values = [1, 2, 3, 4, 5, 6];
// 마지막 순회가 아니면 누적값을 반환하고 마지막 순회면 누적값으로 평균을 구해 반환.
const average = values.reduce((acc, cur, i, { length }) => {
return i === length - 1 ? (acc + cur) / length : acc + cur;
}, 0);
console.log(average); // 3.5
// 최대값 구하기
const values2 = [1, 2, 3, 4, 5];
const max = values2.reduce((acc, cur) => (acc > cur ? acc : cur), 0);
console.log(max); // 5
const max2 = Math.max(...values2);
// var max2 = Math.max2.apply(null, values2);
console.log(max2);
// 요소의 중복 횟수 구하기
const fruits = ["banana", "apple", "orange", "orange", "apple"];
const count = fruits.reduce((acc, cur) => {
// 첫번째 순회시 acc 초기값은 {} cur은 첫번째 요소인 banana
// 초기값으로 전달받은 빈 객체에 요소값인 cur을 프로퍼티 키로, 요소의 개수를 프로퍼티 값으로 할당
// 만약 프로퍼티 값이 undefined (처음 등장하는 요소)이면 프로퍼티 값을 1로 초기화 한다.
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
console.log(count); // {banana: 1, apple: 2, orange: 2}