Intermediate 8 min

Map, filter, and reduce

Array methods express whether you want to transform elements, choose a subset, or combine the array into one result.

How it works

Follow the intermediate list after each step. Filtering [2, 3, 4] produces [2, 4]. Mapping square produces [4, 16]. Reducing those with sum would yield 20. Name intermediate results while learning so you can see which operation changed the shape.

Walk through an example

Map keeps one output for each input. Filter keeps matching entries. Reduce updates an accumulator, such as a running sum, as it visits each item.

What to watch for

Give reduce an explicit initial value when the array may be empty. For sums, use 0 so the answer for an empty list is defined.

Code example

const values = [2, 3, 4];
const squares = values.filter(n => n % 2 === 0).map(n => n * n);
console.log(squares);

Check your understanding

What array results?

See the example and explanation
Worked example
Given [2, 3, 4], keep even numbers and then square them
Answer [4, 16]

Filter keeps 2 and 4. Map computes 2 × 2 and 4 × 4.

Open practice problem
Next lessonThe DOM and browser events