Mastering Array Methods in Modern JavaScript
map, filter, reduce, and friends — when to use each and how to compose them without losing readability.
Array methods replaced most for loops. Knowing when each one fits keeps chains readable.
map: transform every element
Use map when output length equals input length. Never mutate inside it.
const prices = [100, 200, 300];
const withTax = prices.map(p => p * 1.1); // [110, 220, 330]
filter: keep matching elements
const active = users.filter(u => u.active);
Chain with map to transform after filtering. Filter first to reduce work.
const names = users
.filter(u => u.active)
.map(u => u.name);
reduce: fold into a single value
Reach for it when you need a shape change: array to object, array to number.
const total = cart.reduce((sum, item) => sum + item.price, 0);
const byId = users.reduce((acc, user) => {
acc[user.id] = user;
return acc;
}, {});
find vs filter
find returns the first match and stops. Use it when you expect one result.
const admin = users.find(u => u.role === 'admin');
flatMap
flatMap is map plus one level of flatten. Useful when each element maps to zero or more results.
const sentences = paragraphs.flatMap(p => p.split('. '));
When to skip array methods
Deep nesting of map/filter/reduce hurts readability more than a for...of loop. If you need early exit, for...of with break is cleaner.
Keep reading
Related posts
Writing Clean Functions in JavaScript
Small, focused functions make code easier to test, read, and maintain without over-engineering.
TypeScript Generics Without the Headache
A practical guide to writing reusable, type-safe functions using generics — without over-abstracting.
K3s Single Node: From Zero to Publicly Accessible
Set up k3s on a single node, deploy an app, configure Ingress, DNS, and TLS — everything needed to expose a service to the internet.