JavaScript/배열

[JavaScript]reduce함수 사용 방법

DevStory 2021. 8. 9.

JavaScript에서 reduce 함수는 배열의 요소를 순차적으로 순회하면서 리듀서(reducer) 함수를 실행하고 하나의 결과값을 반환합니다.

배열 요소의 순회는 initialValue에 설정 유무에 따라 순회를 시작하는 index 0부터 시작할수도 있고 index 1부터 시작할수도 있습니다.

주로 배열 요소의 합계를 계산하는데 사용 되며, 배열 또는 객체로 반환할 수도 있습니다.

arr.reduce(callback(accumulator, currentValue, index, array), initialValue)

arr

- 순회하고자 하는 배열

 

accumulator

- 누적되는 값

- callback 함수의 반환값을 누적

- initialValue를 설정한 경우 callback의 최초 호출시 initialValue로 값으로 초기화

- initialValue가 없을 경우 arr의 0번째 인덱스 값으로 초기화

 

currentValue

- 현재 배열의 요소

 

index(생략 가능)

- 현재 배열 요소의 index

 

array(생략 가능)

- reduce 함수를 호출한 배열

 

initialValue(생략 가능)

- callback의 최초 호출시 accumulator 초기값

 

이번 포스팅에서는 reduce 함수의 사용 방법을 정리하였습니다.

사용 방법
1. 배열 요소의 총 합
2. 객체 배열에서의 값 합산

 

응용 방법은 mozilla에서 많은 예제를 설명하고 있으므로 아래 링크에서 확인해주세요.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

 

Array.prototype.reduce() - JavaScript | MDN

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

developer.mozilla.org


배열 요소의 총 합

initialValue가 설정되어 있지 않으므로 accumulator의 초기값은 0번째 index의 값인 1이며, index 1부터 순회합니다.

순회하면서 배열 요소의 값을 누산기(accumulator)에 누적합니다.

var arr = [1, 2, 3, 4, 5];

var totalValue = arr.reduce(function(accumulator, currentValue, index) {
  console.log(`*****${index}번째 index*****`);
  console.log(`accumulator : ${accumulator}`);
  console.log(`currentValue : ${currentValue}`);
  console.log('\n');
  return accumulator + currentValue;
})

console.log(`totalValue : ${totalValue}`);

실행 결과


객체 배열에서의 값 합산

객체 배열에서 initialValue를 설정하지 않으면, accumulator가 객체이므로 정상적으로 계산이 되지 않습니다.

var arr = [{value : 1}, {value : 2}, {value : 3}];

var totalValue = arr.reduce(function(accumulator, currentValue, index) {
  console.log(`*****${index}번째 index*****`);
  console.log(accumulator);
  console.log(currentValue);
  console.log('\n');
  return accumulator + currentValue.value;
})

console.log(`totalValue : ${totalValue}`);

실행 결과

initialValue를 설정하지 않은 경우

initialValue를 설정하여 위 코드를 정상적으로 동작하도록 처리하였습니다.

accumulatorinitialValue의 값으로 초기화되고 index 0부터 순회를 시작합니다.

var arr = [{value : 1}, {value : 2}, {value : 3}];

var totalValue = arr.reduce(function(accumulator, currentValue, index) {
  console.log(`*****${index}번째 index*****`);
  console.log(accumulator);
  console.log(currentValue);
  console.log('\n');
  return accumulator + currentValue.value;
}, 0)

console.log(`totalValue : ${totalValue}`);

실행 결과

initialValue를 설정한 경우

 

반응형

댓글