본문으로 건너뛰기
yceffort
PostsSeriesTagsAbout🧪 Research
EN

Tweaks

theme
accent palette
film grain
minimal mode
BACK TO INDEX
◆ ESSAY
--min
--year
KOoriginal

mailMail icongithubtwitter
yceffort
•
© 2026
•
https://yceffort.kr
BACK TO INDEX
◆ ESSAY

Javascript Reduce

avatar
yceffort
2019-07-22 · 2분
2min
2019year
KOoriginal
javascript

멍청이라 그런지 reduce 함수가 잘 이해 되지 않았다.

Reduce

const list = [1, 2, 3, 4, 5]
const initValue = 10
const totalSum = list.reduce(
  (accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue
  },
  initValue,
)
25
  • currentValue: 처리할 현재 요소
  • currentIndex (optional): 처리할 요소의 인덱스
  • accumulator: 콜백의 반환값을 계속해서 누적한다. 이 예제에서는 처음엔 1, 그 다음엔 1 + currentValue, 그 다음엔 (1 + currentValue) + currentValue 가 될 것이다.
  • array (optional): reduce를 호출한 배열, 여기서는 list = [1, 2, 3, 4, 5]이 될 것이다.
  • initValue (optional): reduce의 최초 값. 없으면 배열의 0번째 값이 된다. 이 예제에서는 initValue값이 10 이라서, 최종결과는 10 + (1 + 2 ... + 5) 이 될 것이다.
callaccumulatorcurrentValuecurrentIndexarrayreturn
1st1010[1,2,3,4,5]11
2nd1121[1,2,3,4,5]13
3rd1332[1,2,3,4,5]16
4th1643[1,2,3,4,5]20
5th2054[1,2,3,4,5]25

중첩 배열 펼치기

const complicatedList = [[0, 1], [2, 3], [4], [5, 6]]
complicatedList.reduce(
  (accumulator, currentValue) => accumulator.concat(currentValue),
  [],
)
[0, 1, 2, 3, 4, 5, 6]

이보다 더 괴랄한 array의 경우에도 재귀를 사용하여 가능하다.

const moreComplicatedList = [[0, 1], [[[2, 3]]], [[4, 5]], 6]

const flatten = function (arr, result = []) {
  for (let i = 0, length = arr.length; i < length; i++) {
    const value = arr[i]
    if (Array.isArray(value)) {
      flatten(value, result)
    } else {
      result.push(value)
    }
  }
  return result
}

flatten(moreComplicatedList)
[0, 1, 2, 3, 4, 5, 6]

관련 글

  • #javascript#web-performance#algorithm

    reduce에 spread 를 쓰면 안되는 이유

    솔직히 뭔가 멋있어서 많이 쓰긴 함

    2021-06-22·4분
  • #javascript

    javascript 일반 함수와 화살표 함수의 차이

    ES6에서부터 생긴 `arrow function`은 일반적으로 `()=>{}`의 모양을 하고 있으며, 동작도 비슷해보인다. 하지만 이 두 선언방식은 두가지 분명한 차이를 가지고 있다. 하지만 그전에 this를 알아야 한다.

    2020-05-19·3분
  • #javascript

    Javascript - Closure

    자바스크립트의 클로져

    2019-05-09·8분
  • #javascript

    자바스크립트 커링과 클로져

    ## 커링 [이 글](https://www.sitepoint.com/currying-in-functional-javascript/) 에 잘 정리 되어 있습니다. Currying은 여러 개의 인자를 가진 함수를 호출 할 경우, 파라미터의 수보다 적은 수의 파라미터를 인자로 받으면 누락된 파라미터를 인자로 받는 기법을 말한다. 즉 커링은 함수 하나가 n개...

    2020-03-05·2분

새 글을 놓치고 싶지 않으시다면 RSS로 구독해 주세요.

RSS 구독 →

yceffort — 프론트엔드 엔지니어입니다.

← Back to the blogIssue on GitHub →