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]
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]
πΈ 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 νΈμΆ μμ΄ λ°ννλ€.