Languages/Javascript

Javascript-reduce

Tonkatsu 2021. 11. 9. 02:32

JS의 reduce 메서드는 빈 원소를 제외하고 배열 내의 모든 원소에 callback 함수를 실행하는 메서드이다.

 

말만 듣고는 잘 이해가 안간다.

배열의 모든 원소를 합치는 예시는 아래와 같다.

 

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

 

reduce안에 accumulator와 currentValue 를 합치는 function이 있고, 그 function이 [0, 1, 2, 3]을 돌면서 모든 원소에 작동하므로 원소의 모든 합인 6을 반환다.

 

accumulator와 currentValue 말고도 다른 input이 있다.

 

  • callback
    1. accumulator
      • 콜백 함수의 누적합입니다.
      • initialValue가 있는 경우 처음에는 initialValue 값을 가집니다.
    2. currentValue
    3. currentIndex (Optional)
      • 현재 요소의 인덱스입니다.
      • initialValue가 있는 경우 처음에는 0, 없는 경우는 1을 가집니다.
    4. array (Optional)
  • initialValue (Optional)
    • 콜백 최초에 첫 번째 인수에 제공하는 값입니다.
    • 간단하게 생각하면 배열의 0번째에 initialValue를 넣고 reduce를 실행한다 생각해도 됩니다.
    • 없는 경우에는 배열의 첫 번째 요소를 사용합니다.

 

같은 배열에 initialValue가 있고 없고의 차이는 다음 예시를 보면 이해가 쉽다.

 

const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

 

일반적인 reduce의 작동방식을 나타낸 설명은 아래와 같다.

 

 

아래는 모두 사용 예시이다.

 

배열 원소의 합

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// sum is 6

var total = [ 0, 1, 2, 3 ].reduce(
  ( accumulator, currentValue ) => accumulator + currentValue,
  0
);
// sum is 6

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
},initialValue)
console.log(sum) // logs 6

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    ,initialValue
);
console.log(sum) // logs 6

 

배열 합치기

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue);
  },
  []
);

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( accumulator, currentValue ) => accumulator.concat(currentValue),
  []
);
// 펼친 결과: [0, 1, 2, 3, 4, 5]
  • 배열 원소 세기
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

 

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