← Back to the Build Your Homepage series
EPISODE 04
map · filter · reduce · find · sort

Arrays

Stop writing for-loops for array transformations. Use map, filter, reduce, find, and sort — the bread and butter of modern JavaScript.

arraymapfilterreduceimmutability
Duration
About 2 hours
Level
📊 Beginner+
Prerequisite
🎯 js-03
OUTCOME
Transform any array declaratively without manual loops

What you'll learn

  • 1Use map to transform each item
  • 2Use filter to keep matching items
  • 3Use reduce to collapse to a single value
  • 4Use find, some, every, includes for queries

1. map, filter, reduce

javascript
const nums = [1, 2, 3, 4, 5];

const doubled = nums.map(n => n * 2);          // [2, 4, 6, 8, 10]
const evens   = nums.filter(n => n % 2 === 0); // [2, 4]
const sum     = nums.reduce((acc, n) => acc + n, 0); // 15

// Chain them
const sumOfDoubledEvens = nums
  .filter(n => n % 2 === 0)
  .map(n => n * 2)
  .reduce((a, b) => a + b, 0);   // 12

2. Query Methods

javascript
const users = [
  { name: "Alice", age: 30 },
  { name: "Bob",   age: 25 },
];

users.find(u => u.age > 28);     // { name: "Alice", age: 30 }
users.findIndex(u => u.name === "Bob"); // 1
users.some(u => u.age > 50);     // false
users.every(u => u.age > 20);    // true
nums.includes(3);                 // true

3. Sorting (Immutable)

javascript
const sorted = [...nums].sort((a, b) => a - b);    // ascending
const desc   = [...nums].sort((a, b) => b - a);    // descending
const byAge  = [...users].sort((a, b) => a.age - b.age);
⚠️

sort() mutates the original array. Spread it first ([...arr].sort()) to keep the original untouched.

4. Other Useful Methods

javascript
nums.slice(1, 3);           // [2, 3] (immutable)
nums.concat([6, 7]);        // [1,2,3,4,5,6,7]
nums.join(", ");            // "1, 2, 3, 4, 5"
Array.from({ length: 3 }, (_, i) => i * 2);  // [0, 2, 4]
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗