M

reduce() 본문

JavaScript

reduce()

M_master 2022. 5. 11. 16:49

reduce - 요소에 대한 계산 값을 반환 후 다시 계산해서 전달한다. 최종적으로는 단일 값이 나온다.

 

매개변수

  • previousValue : 이전 호출의 결과 값 callbackFn, initialValue 값이 지정이 안 된 경우 array[0] 값으로 설정
  • currentValue : 현재 요소의 값, initialValue 값이 지정되어 있으면 array[0], 그렇지 않으면 array[1]로 설정
  • currentIndex : 배열에서의 인덱스 위치, initialValue 이 설정 된 경우 0, 그렇지 않으면 1
  • array : 순회할 배열
  • initialValue : 콜백이 처음 호출될 때 previousValue가 초기화 되는 값

Syntax

// Arrow function
reduce((previousValue, currentValue) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)

// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)

예제 코드

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

const initialValue = 0;
const sumWithInitial = array1.reduce(function(previousValue, currentValue, currentIndex, array) {
  console.log("previousValue", previousValue);
  console.log("currentValue", currentValue);
  console.log("currentIndex", currentIndex);
  console.log("array", array);
  
  return previousValue + currentValue;
},initialValue);

console.log(sumWithInitial);

실행

// step 1
> "previousValue" 0
> "currentValue" 1
> "currentIndex" 0
> "array" Array [1, 2, 3, 4]
> return 0 + 1 // previousValue + currentValue

// step 2
> "previousValue" 1
> "currentValue" 2
> "currentIndex" 1
> "array" Array [1, 2, 3, 4]
> return 1 + 2 // previousValue + currentValue

// step 3
> "previousValue" 3
> "currentValue" 3
> "currentIndex" 2
> "array" Array [1, 2, 3, 4]
> return 3 + 3 // previousValue + currentValue

// step 4
> "previousValue" 6
> "currentValue" 4
> "currentIndex" 3
> "array" Array [1, 2, 3, 4]
> return 6 + 4 // previousValue + currentValue

// 최종 결과
> 10

 

참고

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

728x90

'JavaScript' 카테고리의 다른 글

Promise  (0) 2022.02.24
table excel download  (0) 2022.02.23
(jQuery) serializeObject  (0) 2022.02.23
화면 프린트 기능  (0) 2022.02.18
배열 관련 함수  (0) 2019.10.04