Kodokon kodokon.com

Array methods: map, filter, reduce, find

Learn to transform, filter, and aggregate data with the four array methods most used in real-world projects.

10 min · 3 questions

Open this lesson in Kodokon

In a real project, you spend your time transforming data: a list of products to display, API results to sort, a cart to total up. The map, filter, reduce, and find methods replace most of your for loops with shorter, more expressive code. They never modify the original array: they return a new result, which prevents a whole class of bugs.

JAVASCRIPT
const products = [
  { name: "keyboard", price: 49, inStock: true },
  { name: "mouse", price: 25, inStock: false },
  { name: "screen", price: 199, inStock: true }
];

const names = products.map((product) => product.name);
console.log(names); // ["keyboard", "mouse", "screen"]
map transforms each element and returns a new array of the same length.

filter keeps only the elements that pass a test and returns a new array, possibly empty. find stops at the first matching element and returns the element itself, or undefined if nothing matches. Mental exercise: to get all the products in stock, which one do you pick? And to get the product named "mouse"?

JAVASCRIPT
const available = products.filter((p) => p.inStock);
console.log(available.length); // 2

const mouse = products.find((p) => p.name === "mouse");
console.log(mouse.price); // 25
filter returns an array, find returns a single element.

reduce is the most powerful: it reduces an array to a single value (a number, an object, a string). It takes a function with an accumulator and the current element, plus an initial value. Classic use case: computing a cart total.

JAVASCRIPT
const cart = [
  { label: "T-shirt", quantity: 2, unitPrice: 15 },
  { label: "Cap", quantity: 1, unitPrice: 12 }
];

const total = cart.reduce(
  (sum, item) => sum + item.quantity * item.unitPrice,
  0
);
console.log(total); // 42
The sum accumulator starts at 0, the initial value passed as the second argument.

To pick the right method, ask yourself one question: what shape should the result have? As many elements as the original but transformed: map. A subset: filter. A single element: find. A single computed value: reduce. This reflex will save you precious time in interviews and on projects alike.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which method always returns an array of the same length as the original array?
    • filter
    • map
    • reduce
    • find
  2. What does find return if no element satisfies the condition?
    • null
    • undefined
    • An empty array
    • An error is thrown
  3. In cart.reduce((sum, item) => sum + item.unitPrice, 0), what is the final 0 for?
    • It's the initial value of the sum accumulator
    • It's the starting index of the traversal
    • It's the value returned if the array is invalid