2 min read

Map, Filter, and Reduce

These are three powerful array methods in JavaScript that allow you to process and transform data in a functional programming style. They all take a callback function as an argument and do not mutate the original array (they return a new one).

1. map()

The map() method creates a new array by applying a function to every element in the calling array.

  • Use when: You want to transform elements.
  • Input: Array of length N.
  • Output: New Array of length N.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8]

2. filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  • Use when: You want to select a subset of elements.
  • Input: Array of length N.
  • Output: New Array of length 0 to N.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4, 6]

3. reduce()

The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

  • Use when: You want to derive a single value (number, object, another array) from the array.
  • Input: Array of length N.
  • Output: Single value.

Syntax: array.reduce(callback(accumulator, currentValue), initialValue)

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // 10

4. Chaining

Since map and filter return arrays, you can chain them together.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Get the squares of even numbers
const result = numbers
  .filter(n => n % 2 === 0) // [2, 4, 6, 8, 10]
  .map(n => n * n);         // [4, 16, 36, 64, 100]

console.log(result);

programming/javascript/vanilla/javascript programming/javascript/vanilla/es6-features