Will find a way

[JS] reduce() 에 대해서 본문

Language/Javascript

[JS] reduce() 에 대해서

Jaka_Park 2024. 6. 20. 08:51

reduce란?

reduce() 메서드는 배열의 요소를 하나로 줄이는 작업을 수행하는 함수다.

reduce 함수로 배열의 각 요소를 순회하면서 누적된 값을 계산하고 최종 결과를 반환할 수 있다.

reduce 형태

array.reduce(callback[, initialValue]);

array : reduce를 적용할 배열
callback : 배열의 각 요소에 대해 실행할 콜백 함수. 콜백함수는 다음과 같은 매개변수를 가진다
- accumulator : 콜백 함수의 반환 값 또는 이전 순회에서의 최종 결과값. 초기값이 제공된 경우 첫번째 순회에서는 initialValue로 설정 된다.
- currentValue : 현재 순회 중인 배열의 요소
- currentIndex (옵션) : 현재 순회 중인 배열의 요소 인덱스
- array ( 옵션) : reduce 함수가 호출된 배열

 

initialValue (옵션) : 콜백 함수의 첫번째 순회에서 accumulator로 사용될 초기 값 초기 값이 제공되지 않으면 배열의 첫번째 요소가 초기값이 된다.

 

반환 값

배열을 순서대로 불러 각 요소에 대해 콜백함수 실행한 결과를 누적한 값

 

1. 배열값 모두 더하기

const num = [1, 2, 3, 4, 5]

const sum = num.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // 출력값 : 15​



2. 객체가 들어간 배열에서 원하는 값만 더하기

const student = [
  {
    name : "jaka1",
    age : 30
  },
  {
    name : "jaka2",
    age : 40
  },
  {
    name : "jaka3",
    age : 50
  }
]

const sumAge = student.reduce((acculmulator, currentValue) => acculmulator + currentValue.age,0);

console.log(sumAge); // 출력값 : 120

 

3. 중첩 배열 배열로 만들기

const numArray = [
  [0, 1],
  [2, 3],
  [4, 5]
]

console.log(numArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);

// 출력값 : [0, 1, 2, 3, 4, 5]

 

'Language > Javascript' 카테고리의 다른 글

[JS] Class 작동원리  (0) 2024.11.15
[JS] 클로저와 스코프  (0) 2024.10.17
[JS] 동기(synchronous) 비동기(asynchronous)  (0) 2024.05.13
[JS] 구조 분해 할당  (0) 2024.04.24
[JS] 쿠키 세션 로컬스토리지  (0) 2024.04.23