본문으로 건너뛰기
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]

관련 글

  • #turbopack#nextjs#bundler

    Next.js turbopack에서 싱글톤이 두 개가 됐다: scope hoisting 버그와 순환 import

    Next.js 16 turbopack 프로덕션 빌드에서 모듈 스코프 싱글톤이 런타임에 두 개가 됐다. 같은 동기 구간에서 조건 판정이 뒤집히고, 응답이 도착해도 타임아웃이 나는 증상을 번들 산출물로 추적한 기록. scope hoisting의 부분 병합, 순환 import, 이미 고쳐져 있던 upstream 버그, 그리고 뒤늦게 돌린 단일 변수 실험까지.

    2026-08-19·28분
  • #javascript#animation#web-animations-api

    number-flow를 구형 브라우저로 이식하기: 다섯 가지 결정과 두 가지 번복

    number-flow가 애니메이션을 켜는 최소 버전은 Chrome 125, Safari 17.2다. 이 하한을 Chrome 66과 WebKit 16.4까지 내리는 포크를 만들면서 내린 결정들과, 뒤집게 된 판단 두 가지, 그리고 자동 강등을 포기한 Safari 버그 조사의 기록.

    2026-08-11·44분
  • #nodejs#security#javascript

    Node.js vm 모듈의 함정: 샌드박스가 아닌 이유

    집필 중인 Node.js Deep Dive의 5.2장(vm 모듈의 함정) 일부를 미리 공개합니다.

    2026-02-27·25분
  • #nodejs#javascript

    Node.js Deep Dive (가제) 베타 리더를 모십니다.

    많관부22

    2026-02-19·5분

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

RSS 구독 →

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

← Back to the blogIssue on GitHub →