← JavaScript

Arrays & Objects

What is the difference between `map`, `filter`, and `reduce`?

Show answer — try answering out loud first

map transforms each element and returns an array of the same size. filter returns an array containing only the elements that meet a condition. reduce combines all elements into a single value. All three return something new and never modify the original array.

  • map: applies a function to each element and returns a new array with the results. The same number of elements.
  • filter: evaluates each element against a condition and returns a new array with only the ones that return true.
  • reduce: iterates over the array accumulating a result. Useful for summing, counting, grouping, etc. Returns a single value.

None of them modifies the original array: all three return something new.

const numeros = [1, 2, 3, 4, 5];

// map: transforms (doubles each number)
const dobles = numeros.map((n) => n * 2);
console.log(dobles); // [2, 4, 6, 8, 10]

// filter: filters (only the even ones)
const pares = numeros.filter((n) => n % 2 === 0);
console.log(pares); // [2, 4]

// reduce: combines (sums everything)
const suma = numeros.reduce((acc, n) => acc + n, 0);
console.log(suma); // 15

// The original array never changed
console.log(numeros); // [1, 2, 3, 4, 5]

// They can be chained
const sumaDePareDuplicados = numeros
  .filter((n) => n % 2 === 0) // [2, 4]
  .map((n) => n * 2)          // [4, 8]
  .reduce((acc, n) => acc + n, 0); // 12
console.log(sumaDePareDuplicados); // 12
  • Forgetting the initial value in reduce (the second argument, 0 in the example). Without it, the behavior changes and it can throw errors with empty arrays.
  • Using map when you don't actually need the resulting array (forEach is the better option there).
  • Forgetting the return when the callback uses braces: map(n => { n * 2 }) returns undefined because the return is missing.

"map transforms each element and returns an array of the same size. filter returns only the elements that meet a condition. reduce iterates over the array accumulating a value until it produces a single result, like a sum or a count. All three are immutable: they don't modify the original array, they return a new one, and they can be chained. With reduce I always remember to provide the accumulator's initial value."

Quick challenge

Given ["hola", "mundo", "js"], use reduce to get the total number of characters across all the words combined.

See answer
const palabras = ["hola", "mundo", "js"];
const totalCaracteres = palabras.reduce((acc, palabra) => acc + palabra.length, 0);
console.log(totalCaracteres); // 11