Web Dev Notes

Array methods cheat sheet

One-line semantics for the methods you use daily, plus a decision table for the moments you forget which one returns what.

The core five

const xs = [1, 2, 3, 4];

xs.map(n => n * 2);          // [2, 4, 6, 8]   same length, transformed
xs.filter(n => n % 2 === 0); // [2, 4]         subset, same values
xs.reduce((a, n) => a + n);  // 10             any type out
xs.find(n => n > 2);         // 3              first match or undefined
xs.some(n => n > 3);         // true           predicate on existence

Decision table

You need…UseReturns
Every item, changedmapnew array
Only matching itemsfilternew array
A single accumulated valuereduceanything
First matching itemfinditem or undefined
Index of a matchfindIndexnumber or -1
Do all / any match?every / someboolean
Flatten + transformflatMapnew array
Sorted copytoSorted (ES2023)new array

Details that matter

// flatMap: map + flatten one level — great for 1-to-many transforms
const sentences = ["hello world", "bye now"];
sentences.flatMap(s => s.split(" "));
// ["hello", "world", "bye", "now"]

Copy vs mutate (ES2023)

const a = [3, 1, 2];
a.toSorted();    // [1, 2, 3]  a unchanged
a.toReversed();  // [2, 1, 3]  a unchanged
a.with(0, 99);   // [99, 1, 2] a unchanged

In shared or long-lived state, the immutable variants prevent a class of bugs where one caller silently reorders data another caller is iterating.

See also