본문 바로가기
개발 공부 일지/JavaScript

자바스크립트 - 배열 메소드 .reduce

by yelimu 2024. 7. 22.

누적값을 구할때 사용하는 메소드

 

const 변수 = 배열.reduce(콜백함수 (acc, el, i, arr) => {

return ~ }, 두번째 아규먼트=초기값) ;


 

 

const numbers = [1, 2, 3, 4];

 

numbers.reduce((acc, el, i, arr) => {

  return nextAccVlaue;       그 다음 콜백함수에 acculator로 전달할 값을 리턴해준다

}, initialAccValue);

 

콜백함수의 첫 번째 파라미터 acc : accumulator

매번 콜백함수가 반복해서 동작할 때 직전에 동작한 콜백함수가 리턴한 값을 전달받는 파라미터

-> acc 가 nextAccValue 를 받는다 

따라서 제일 마지막 콜백함수의 리턴값이 reduce 메소드의 최종 리턴값임

 

 

가장 먼저 콜백함수가 동작할때는 직전 리턴 값이 없으므로 초기값을 두번째 아규먼트로 정해주기

 (optional 이지만 초기값을 명시해주는게 안전하다)

초기값을 제공하지 않으면 reduce는 배열의 첫 번째 요소를 acc로 사용

const numbers = [1, 2, 3, 4];

const sumAll = numbers.reduce((acc, el, i) => {
  console.log(`${i}번 index의 요소로 콜백함수가 동작중입니다.`);
  console.log('acc:', acc);
  console.log('el:', el);
  console.log('-----------');

  return acc + el;
}, 0);

console.log('sumAll:', sumAll);

 

const data = [ 
  { company: 'Naber', month: 3 },
  { company: 'Amajohn', month: 12 },
  { company: 'Coogle', month: 10 },
  { company: 'Ittel', month: 6 },
  { company: 'Sasung', month: 4 },
  { company: 'CaCao', month: 3 },
  { company: 'Microhard', month: 17 },
];

// 여기에 코드를 작성하세요
const totalCareer = data.reduce((acc, el, i, arr) => {
  return acc + el.month;
} ,0);

console.log(`상원이의 경력은 총 ${totalCareer}개월입니다.`);

data의 month 프로퍼티에 접근하려면 배열의 각 요소를 함수 프로퍼티 el로 정의했으므로 el.month 로 사용 

마지막 요소까지 순회하고서 acc + el.month 값이 totalCareer 에 할당됨