반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

taenyLog

[JavaScript] Reduce 본문

Web

[JavaScript] Reduce

taenyLog 2023. 9. 26. 09:00
반응형

Reduce

Executes a reducer function on each element of the array, resulting in a single value.

배열을 가져다가 점차 줄여가면서 마지막에는 결국 하나의 값만 남긴다.

 

 

배열이름.reduce((accumulator,elememt) =>{
    return accumulator + elememt
})

 

 

최댓값, 최솟값 찾기도 가능하다.

ex) 가장 높은 / 낮은 평점을 받은 영화를 찾기

 

 

초기값 없이 reduce()

const array = [15, 16, 17, 18, 19];

function reducer(accumulator, currentValue, index) {
  const returns = accumulator + currentValue;
  console.log(
    `accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
  );
  return returns;
}

array.reduce(reducer);

콜백은 4번 호출

First call 15 16 1 31
Second call 31 17 2 48
Third call 48 18 3 66
Fourth call 66 19 4 85

 

 

 

초기값과 reduce()

[15, 16, 17, 18, 19].reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  10,
);

콜백은 5번 호출

First call 10 15 0 25
Second call 25 16 1 41
Third call 41 17 2 58
Fourth call 58 18 3 76
Fifth call 76 19 4 95

 

 

위의 코드에서 10을 초기값으로 넣어줬기때문에  First call이 10으로 시작하는 것을 볼 수 있다.

반응형