EasyConcept

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

Technology:
JavaScript
Experience:
Intern,
Junior

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.

Detailed explanation

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.

Example

javascript
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
  • JavaScriptEasy

    What is hoisting in JavaScript?

    Hoisting is JavaScript moving declarations to the top of their scope during compilation, so functions and var variables can be referenced before the line where they are written.

    Intern · Junior · Functions & Scope
  • JavaScriptMedium

    What is a closure in JavaScript and why is it useful?

    A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function has finished running.

    Junior · Mid-level · Functions & Scope
  • JavaScriptMedium

    How does the this keyword work in JavaScript?

    this is decided by how a function is called, not where it is written: as a method it is the object before the dot, with new it is the new object, and arrow functions inherit it from the enclosing scope.

    Junior · Mid-level · Functions & Scope