Intern / FresherJavaScript

What is the difference between map, filter and reduce in JavaScript?

Quick answer

map transforms every item into a new array of the same length, filter keeps only items that pass a test, and reduce folds the whole array into a single value.

All three are array methods that do not mutate the original array (when your callback is pure). map returns an array with the same number of items. filter returns a shorter or equal array. reduce takes an accumulator and returns anything: a number, an object, even another array.

They chain well: filter first to reduce the work, then map, then reduce. Forgetting the initial value in reduce is a common bug: on an empty array it throws a TypeError.

const orders = [{ price: 20, paid: true }, { price: 35, paid: false }, { price: 15, paid: true }];

const prices = orders.map(o => o.price);            // [20, 35, 15]
const paid   = orders.filter(o => o.paid);          // 2 orders
const total  = orders
  .filter(o => o.paid)
  .reduce((sum, o) => sum + o.price, 0);            // 35

Key points

  • map: one output per input
  • filter: keeps items where the callback returns truthy
  • reduce: always pass an initial value