[JS] reduce 함수

EUNCHAE KIM·2022년 10월 1일

배열의 각 요소에 대해 주어진 리듀서(reducer)함수를 콜백함수로 실행하고 하나의 결과값을 반환

1) reduce()는 2개의 인자값을 받는다

  • callbackfn : 배열의 각 요소에 실행할 reducer 함수
  • initialValue : 리듀서 함수에 첫번째 누적값으로 제공할 초기 값
    (없으면 배열의 첫번째 요소가 초기값이 됨)

2) reducer 함수는 4개의 인자값을 받는다

  • accumulator : 누적값
  • currentValue : 현재 요소값
  • currentIndex : 현재 요소값의 index
  • array : reduce()를 호출한 배열

3) 사용예시
a. 배열에서의 덧셈 (초기값 없을때 / 있을때)

const arr = [1, 2, 3, 4, 5];
console.log("초기값 없음");
arr.reduce((total, now, nowIdx, arr) => {
console.log("total :", total);
console.log("now :", now);
console.log("nowIdx :", nowIdx);
console.log("arr :", arr);
console.log("\n");
return total + now;
});

console.log("\n초기값 있음");
arr.reduce((total, now, nowIdx, arr) => {
console.log("total :", total);
console.log("now :", now);
console.log("nowIdx :", nowIdx);
console.log("arr :", arr);
console.log("\n");
return total + now;
}, 0);

b. object 배열에서의 활용 -그룹핑

//그룹핑
let people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

let groupedPeople = groupBy(people, 'age')
출처: https://jo-c.tistory.com/54 [조씨의 개발 블로그:티스토리]

c. object 배열에서의 활용 - 카운팅

//카운팅
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

let countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})
출처: https://jo-c.tistory.com/54 [조씨의 개발 블로그:티스토리]


reduce 활용하기

profile
Try Everything

0개의 댓글