JavaScript Array Methods
Arrays come with powerful methods for transformation: `map()` creates a new array by transforming each element, `filter()` keeps elements matching a condition, and `reduce()` combines all elements into a single value.
These functional methods are central to modern JavaScript and are generally preferred over manual for-loops for clarity.
map and filter
`arr.map(fn)` returns a new array with fn applied to every element. `arr.filter(fn)` returns a new array containing only elements where fn returns true.
reduce
`arr.reduce((acc, cur) => acc + cur, 0)` accumulates array elements into a single result, like a running total.
let nums = [1, 2, 3, 4];
let doubled = nums.map(n => n * 2);
console.log(doubled);[2, 4, 6, 8]map transforms every element into a new array.
let nums = [1, 2, 3, 4];
let evens = nums.filter(n => n % 2 === 0);
let sum = nums.reduce((a, b) => a + b, 0);
console.log(evens, sum);[2, 4] 10filter keeps matching elements; reduce sums them all.
Key points
- map() transforms every element into a new array.
- filter() keeps only elements that pass a test.
- reduce() combines all elements into a single accumulated value.
- These methods do not mutate the original array.
