map, filter & reduce

In JavaScript, map, filter, and reduce are powerful array methods used to transform, select, or accumulate values efficiently and declaratively.

Illustration of map, filter & reduce
Illustration of map, filter & reduce

💡 Core Purpose

  • map: Transforms each item and returns a new array of the same length.
  • filter: Selects items based on a condition, returning a subset array.
  • reduce: Combines array items into a single value through a callback.

1. map(): Transform Items

Creates a new array by applying a function to every element of the original array.

📌 Deep Dive: map Example

JAVASCRIPT
const numbers = [1, 2, 3];
const squares = numbers.map(x => x * x);
console.log(squares);
Output
[1, 4, 9]

2. filter(): Select Items

Returns a new array containing only elements that satisfy a provided test function.

📌 Deep Dive: filter Example

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);
Output
[2, 4]

3. reduce(): Accumulate Values

Processes each element to reduce the array to a single value using a reducer function and an optional initial value.

📌 Deep Dive: reduce Example

JAVASCRIPT
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, current) => acc + current, 0);
console.log(sum);
Output
10
Comparison of map, filter & reduce
MethodReturnsPurpose
mapNew array of same lengthTransform each element
filterNew array of filtered elementsSelect elements by condition
reduceSingle value (any type)Combine elements into one value

⚠️ Important

None of these methods mutate the original array. They always return a new value or array.

💡 Common Usage Patterns

  • map for data transformation (e.g., formatting strings, modifying objects)
  • filter for extracting subsets (e.g., active users, valid inputs)
  • reduce for aggregation (e.g., sums, averages, grouping)