Notifications

No notifications

Arrays are JavaScript's everyday workhorse — ordered, dynamic, can hold any mix of values. The killer feature is the *array methods* — map, filter, reduce, find, some, every, sort — which let you write transformations declaratively. Master these and most for-loops disappear from your code.

On this page

Detailed Theory

# Arrays & Array Methods

Creating

const a = [1, 2, 3];
const b = new Array(5);            // length-5 sparse array — avoid
const c = Array.from("abc");       // ["a", "b", "c"]
const d = Array.of(7);             // [7]      (vs new Array(7) → length 7)
const e = Array.from({ length: 5 }, (_, i) => i * i);  // [0, 1, 4, 9, 16]

Mutating methods (modify in place)

methoddoes
push(x)add to end → returns new length
pop()remove from end → returns it
unshift(x)add to start → returns new length
shift()remove from start → returns it
splice(i, n, …)remove n items at i, optionally insert
sort(cmp?)sort in place (string sort by default!)
reverse()reverse in place
fill(v, s?, e?)fill range with value

Non-mutating (return a new array — preferred in modern code)

methoddoes
slice(s, e)shallow copy of a range
concat(arr)merge
[...a, ...b]spread merge (preferred)
map(fn)transform each element
filter(pred)keep matching elements
flat(depth=1)flatten nested arrays
flatMap(fn)map then flat(1)
toSorted(), toReversed(), toSpliced()ES2023 immutable versions

map / filter / reduce — the holy trinity

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

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

// reduce can build anything — frequency map const words = ["a", "b", "a", "c", "a", "b"]; const freq = words.reduce((m, w) => (m[w] = (m[w] || 0) + 1, m), {}); // { a: 3, b: 2, c: 1 }

Find / some / every / includes

const users = [{id:1, admin:true}, {id:2, admin:false}];

users.find(u => u.id === 2); // {id:2, admin:false} users.findIndex(u => u.id === 2); // 1 users.some(u => u.admin); // true — at least one matches users.every(u => u.id > 0); // true — all match nums.includes(3); // true nums.indexOf(3); // 2

sort — the gotcha

Default sort is lexicographic (treats elements as strings). For numbers you MUST pass a comparator.
[10, 2, 1, 20].sort();                       // [1, 10, 2, 20]   ← surprise!
[10, 2, 1, 20].sort((a, b) => a - b);        // [1, 2, 10, 20]   ← ascending
[10, 2, 1, 20].sort((a, b) => b - a);        // [20, 10, 2, 1]   ← descending

// sort objects by a field users.sort((a, b) => a.name.localeCompare(b.name));

// stable since ES2019 — equal elements keep their original order

Destructuring + spread on arrays

const [first, second, ...rest] = [10, 20, 30, 40];   // first=10, second=20, rest=[30,40]

const merged = [...a, ...b]; // concat const copy = [...a]; // shallow copy const swapped = [b[0], a[0]] = [a[0], b[0]]; // swap via destructuring

Common patterns

// unique values
[...new Set([1, 2, 2, 3, 3, 3])];                     // [1, 2, 3]

// chunk const chunk = (arr, n) => arr.reduce((acc, _, i) => (i % n ? acc : [...acc, arr.slice(i, i + n)]), []);

// group by (Object.groupBy — ES2024) Object.groupBy(users, u => u.admin ? "admin" : "user");

Don't mutate when you can return new

React, Redux, Vue — they all rely on detecting *reference changes*. Prefer:
const next = [...prev, item];          // ✅
prev.push(item);                       // ❌ mutates — UI may not re-render