ShaharAmir
← Back to Blog
JavaScript3 min read

Array Methods Cheat Sheet

map, filter, reduce, find, and more — when to use each

S
Shahar Amir

Array Methods Cheat Sheet

Stop writing for loops. Use the right array method.

Transform: map()

Create a new array by transforming each element:

javascript
1234567
const prices = [10, 20, 30];
const doubled = prices.map(p => p * 2);
// [20, 40, 60]
const users = [{ name: "John" }, { name: "Jane" }];
const names = users.map(u => u.name);
// ["John", "Jane"]

Filter: filter()

Keep elements that pass a test:

javascript
12345678910
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]
const users = [
{ name: "John", active: true },
{ name: "Jane", active: false },
];
const activeUsers = users.filter(u => u.active);
// [{ name: "John", active: true }]

Find One: find() & findIndex()

Get the first match:

javascript
12345678910
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
];
const jane = users.find(u => u.name === "Jane");
// { id: 2, name: "Jane" }
const janeIndex = users.findIndex(u => u.name === "Jane");
// 1

Check: some() & every()

Test conditions:

javascript
1234
const ages = [18, 21, 25, 16];
ages.some(age => age < 18); // true (at least one)
ages.every(age => age >= 18); // false (not all)

Accumulate: reduce()

Combine all elements into one value:

javascript
123456789101112131415161718
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 10
const items = [
{ name: "Apple", price: 1 },
{ name: "Banana", price: 2 },
];
const total = items.reduce((acc, item) => acc + item.price, 0);
// 3
// Group by category
const grouped = items.reduce((acc, item) => {
const key = item.category;
acc[key] = acc[key] || [];
acc[key].push(item);
return acc;
}, {});

Check Existence: includes()

javascript
123
const fruits = ["apple", "banana", "orange"];
fruits.includes("banana"); // true
fruits.includes("grape"); // false

Flatten: flat() & flatMap()

javascript
12345
const nested = [[1, 2], [3, 4]];
nested.flat(); // [1, 2, 3, 4]
const users = [{ tags: ["a", "b"] }, { tags: ["c"] }];
users.flatMap(u => u.tags); // ["a", "b", "c"]

Sort: sort()

javascript
123456
const numbers = [3, 1, 4, 1, 5];
numbers.sort((a, b) => a - b); // [1, 1, 3, 4, 5]
const users = [{ name: "Zoe" }, { name: "Amy" }];
users.sort((a, b) => a.name.localeCompare(b.name));
// [{ name: "Amy" }, { name: "Zoe" }]

Quick Reference

MethodReturnsUse when
`map`New arrayTransform each item
`filter`New arrayKeep matching items
`find`One itemGet first match
`some`BooleanCheck if any match
`every`BooleanCheck if all match
`reduce`Any valueAccumulate/combine
`includes`BooleanCheck existence
`flat`New arrayFlatten nested
`sort`Same arrayOrder items
Master these and you'll rarely need a for loop.

#arrays#methods#fundamentals

Stay Updated 📬

Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.