avatar
Published on

Javascript Reduce

Author
  • avatar
    Name
    yceffort

๋ฉ์ฒญ์ด๋ผ ๊ทธ๋Ÿฐ์ง€ 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]