map, filter, reduce

김병엽·2024λ…„ 7μ›” 11일

map

  • create a new array by applying a function to each element of the original array.

  • not modify the original array.

πŸ”Έ Key Points:

  • Transforms each element of the array.
  • Returns a new array of the same length.
  • Does not change the original array.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // Output: [2, 4, 6, 8, 10]
console.log(numbers); // Output: [1, 2, 3, 4, 5]

filter

  • create a new array with all elements that pass the test implemented by the provided function.

  • not modify the original array.

πŸ”Έ Key Points:

  • Filters elements based on a condition.
  • Returns a new array with only the elements that pass the test.
  • Does not change the original array.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]
console.log(numbers); // Output: [1, 2, 3, 4, 5]

reduce

  • apply a function against an accumulator and each element in the array to reduce it to a single value.

πŸ”Έ Key Points:

  • Reduces the array to a single value.
  • Takes a callback function with an accumulator and current value as arguments.
  • The initial value of the accumulator can be specified.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15
console.log(numbers); // Output: [1, 2, 3, 4, 5]

reduce() ν•¨μˆ˜ ν˜ΈμΆœμ—μ„œ initialValueλ₯Ό μ œκ³΅ν•œ 경우, accumulatorλŠ” initialValue와 κ°™κ³  currentValueλŠ” λ°°μ—΄μ˜ 첫 번째 κ°’κ³Ό κ°™λ‹€.

initialValueλ₯Ό μ œκ³΅ν•˜μ§€ μ•Šμ•˜λ‹€λ©΄, accumulatorλŠ” λ°°μ—΄μ˜ 첫 번째 κ°’κ³Ό κ°™κ³  currentValueλŠ” 두 λ²ˆμ§Έμ™€ κ°™λ‹€.

배열이 λΉ„μ–΄μžˆλŠ”λ° initialValue도 μ œκ³΅ν•˜μ§€ μ•ŠμœΌλ©΄ TypeErrorκ°€ λ°œμƒν•œλ‹€.

λ°°μ—΄μ˜ μš”μ†Œκ°€ (μœ„μΉ˜μ™€ 관계없이) ν•˜λ‚˜ λΏμ΄λ©΄μ„œ initialValueλ₯Ό μ œκ³΅λ˜μ§€ μ•Šμ€ 경우, λ˜λŠ” initialValueλŠ” μ£Όμ–΄μ‘ŒμœΌλ‚˜ 배열이 빈 κ²½μš°μ—” κ·Έ 단독 값을 callback 호좜 없이 λ°˜ν™˜ν•œλ‹€.


Reference

MDN
code4Web

profile
μ„ ν•œ 영ν–₯λ ₯을 쀄 수 μžˆλŠ” κ°œλ°œμžκ°€ 되자, λ˜κ³ μ‹Άλ‹€.

0개의 λŒ“κΈ€