μλ°μ€ν¬λ¦½νΈ λ‘μ§μμ μμ£Ό μ¬μ©νλ methodμ λν΄ μ 리ν΄λ³΄μβοΈ
reduce() λ©μλλ λ°°μ΄μ κ° μμμ λν΄ μ£Όμ΄μ§ 리λμ(reducer) ν¨μλ₯Ό μ€ννκ³ , νλμ κ²°κ³Όκ°μ λ°νν©λλ€.
arr.reduce(callback[, initialValue])
리λμ ν¨μλ λ€ κ°μ μΈμλ₯Ό κ°μ§λλ€.
- λμ°κΈ°accumulator (acc)
- νμ¬ κ° (cur)
- νμ¬ μΈλ±μ€ (idx)
- μλ³Έ λ°°μ΄ (src)
π 리λμ ν¨μμ λ°ν κ°μ λμ°κΈ°μ ν λΉλκ³ , λμ°κΈ°λ μν μ€ μ μ§λλ―λ‘ κ²°κ΅ μ΅μ’ κ²°κ³Όλ νλμ κ°μ΄ λ©λλ€.
const firstName = ["Lee", "Kim", "Park", "Park", "Lee", "Kim", "Park"]; const reducer = function(accumulator, value, index, array) { if (accumulator.hasOwnProperty(value)) { accumulator[val] = accumulator[val] + 1; } else { accumulator[val] = 1; } return accumulator; } const initialValue = {}; const result = votes.reduce(reducer, initialValue); console.log(result); // { Kim: 2, Park: 3, Lee: 2 }
μκΈ° μ½λλ firstName λ°°μ΄μ μλ κ°λ€μ μννλ©΄μ μ΅μ’ μ μΌλ‘ κ°κ°μ κ°λ€μ΄ λͺ λ² λμ€λμ§ count νλ λ‘μ§μ λλ€. reduce λ©μλμ 첫 λ²μ§Έ μΈμλ‘λ reducer λΌλ ν¨μλ₯Ό, λ λ²μ§Έ μΈμλ‘λ μ΄κΈ°κ°, intialValue λΌλ λΉ object λ₯Ό μ λ¬ν©λλ€.
λ°°μ΄μ 첫 λ²μ§Έ μν λλ accumulator μ κ°μ initialValue, μ¦ {} μ λλ€. if 쑰건κ²μ¬μ κ²°κ³Όλ false μ΄λ―λ‘ accumulator.kim = 1 μ΄ λκ³ , { βkimβ : 1 } μ΄λΌλ κ°μ return ν©λλ€.
λ λ²μ§Έ μν λλ accumulator μ κ°μ μμμ μ λ¬λ°μ { βkimβ : 1 } μ΄κ³ , value λ λ°°μ΄μ λ λ²μ§Έ κ°(votes[1])μΈ βhongβ μ΄λ―λ‘ return νλ κ°μ { βkimβ : 1, βhongβ : 1 } μ λλ€. μ΄λ κ² κ³μν΄μ λ°°μ΄μ λκΉμ§ μννλ©΄ μ΅μ’ μ μΈ κ²°κ³Όλ { kim: 1, hong: 3, lee: 3} μ κ°μ΅λλ€.
map() λ©μλλ λ°°μ΄ λ΄μ λͺ¨λ μμ κ°κ°μ λνμ¬ μ£Όμ΄μ§ ν¨μλ₯Ό νΈμΆν κ²°κ³Όλ₯Ό λͺ¨μ μλ‘μ΄ λ°°μ΄μ λ°νν©λλ€.
arr.map(callback(currentValue[, index[, array]])[, thisArg])
맀κ°λ³μ
- callback
μλ‘μ΄ λ°°μ΄ μμλ₯Ό μμ±νλ ν¨μ. λ€μ μΈ κ°μ§ μΈμλ₯Ό κ°μ§λλ€.- currentValue
μ²λ¦¬ν νμ¬ μμ.- index Optional
μ²λ¦¬ν νμ¬ μμμ μΈλ±μ€.- array Optional
map()μ νΈμΆν λ°°μ΄.- thisArg Optional
callbackμ μ€νν λ thisλ‘ μ¬μ©λλ κ°.- λ°ν κ°
λ°°μ΄μ κ° μμμ λν΄ μ€νν callbackμ κ²°κ³Όλ₯Ό λͺ¨μ μλ‘μ΄ λ°°μ΄.
forEach() λ©μλλ μ£Όμ΄μ§ ν¨μλ₯Ό λ°°μ΄ μμ κ°κ°μ λν΄ μ€νν©λλ€.
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
맀κ°λ³μ
- callback
κ° μμμ λν΄ μ€νν ν¨μ. λ€μ μΈ κ°μ§ 맀κ°λ³μλ₯Ό λ°μ΅λλ€.- currentValue
μ²λ¦¬ν νμ¬ μμ.- index Optional
μ²λ¦¬ν νμ¬ μμμ μΈλ±μ€.- array Optional
forEach()λ₯Ό νΈμΆν λ°°μ΄.- thisArg Optional
callbackμ μ€νν λ thisλ‘ μ¬μ©ν κ°.- λ°ν κ°
undefined
forEach μ map μ 1λ²μ§Έ μ λ¬μΈμλ‘ ν¨μλ₯Ό λ°λλ€. κ·Έλ¦¬κ³ κ·Έ ν¨μλ μΈ κ°μ μΈμλ₯Ό κ°μ§κ³ νΈμΆμ΄ λλλ° 1λ²μ§Έλ λ°°μ΄ μμμ κ°, 2λ²μ§Έλ κ·Έκ²μ μΈλ±μ€, 3λ²μ§Έλ λ°°μ΄ κ·Έ μ체μ λλ€(λ³΄ν΅ 1λ²λ§ μ¬μ©)
forEach μ map λ λ€ λ°°μ΄μ μννλ©° μΈμλ‘ μ λ¬ν μμμ κ°μ κ°μ§κ³ ν¨μ λ‘μ§μ ꡬννλ€λ κ²μμ 곡ν΅μ μ΄ μλ€. νμ§λ§, κ·Όλ³Έμ μΌλ‘ return μ΄ μ‘΄μ¬ μ 무μμ μ°¨μ΄κ° μλ€.
μ΄λ€ λ°°μ΄μ΄ μμ λ λ°°μ΄μ μννλ©° μμμ κ°λ€μ κ°κ° κ°κ³΅ν΄μ μμ λ/μλ‘μ΄ λ°°μ΄(μλ λ°°μ΄κ³Ό κΈΈμ΄κ° λκ°μ)μ return λ°κ³ μ νλ€λ©΄ map λ©μλλ₯Ό, κ·Έλ μ§ μκ³ μμμ κ°λ€μ νμ©ν΄μ μμλ€μ ν©μ΄λ, νκ· μ ꡬνκ³ μ νλ€λ©΄, κ·Έλ¦¬κ³ μλ λ°°μ΄κ³Όλ κΈΈμ΄κ° λ€λ₯Έ λ°°μ΄ κ²°κ³Όλ₯Ό λ°κ³ μΆλ€λ©΄, forEach λ₯Ό μ°λ©΄ λ κ² κ°λ€