JavaScript ยท Chapter 22 of 55

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.

Example 1 (javascript)
let nums = [1, 2, 3, 4];
let doubled = nums.map(n => n * 2);
console.log(doubled);
Output
[2, 4, 6, 8]

map transforms every element into a new array.

Example 2 (javascript)
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);
Output
[2, 4] 10

filter 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.
๐Ÿ’ก Note: Chaining map/filter/reduce together is a common, readable pattern for data processing.

๐Ÿ“ Quick Quiz

1. Which method transforms every array element?

2. Which method keeps only elements passing a test?

3. Which method reduces an array to a single value?