본문으로 건너뛰기
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#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분
  • #javascript#frontend#web-performance

    IntersectionObserver 싱글톤 패턴과 WeakMap으로 메모리 누수 방지하기

    수백 개의 요소를 효율적으로 관찰하면서 메모리 누수도 방지하는 방법

    2026-01-17·20분

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

RSS 구독 →

yceffort — 프론트엔드 엔지니어입니다. 발표·기술 자문·기고 문의는 이곳에서 받고 있습니다.

← Back to the blogIssue on GitHub →