Arrays and iteration
The methods that replace most for-loops — map, filter, reduce, find — and when mutation versus copying matters.
Transformation methods
const nums = [4, 1, 8, 3];
nums.map(n => n * 2); // [8, 2, 16, 6] same length
nums.filter(n => n > 3); // [4, 8] subset
nums.find(n => n > 3); // 4 first match
nums.findIndex(n => n > 3); // 0
nums.reduce((t, n) => t + n, 0); // 16 collapse to one value
nums.some(n => n > 7); // true
nums.every(n => n > 0); // true| Method | Returns | Mutates? |
|---|---|---|
map/filter/slice/concat | new array | No |
push/pop/shift/unshift | length/element | Yes |
splice | removed items | Yes |
sort/reverse | the array itself | Yes |
reduce | anything | Depends on your callback |
⚠️
sort() converts elements to strings by default, so [10, 9].sort() gives [10, 9]. Always pass a comparator: arr.sort((a, b) => a - b).Looping choices
for (const item of nums) console.log(item); // values
for (const [i, item] of nums.entries()) console.log(i, item);
nums.forEach(n => console.log(n)); // no break/continue
// never use for...in for arrays - it walks enumerable keys
for (const k in nums) console.log(k); // '0','1',... plus inherited surprisesfor…offor values, supportsbreak/await.for…inenumerates keys and is meant for plain objects.forEachcannot be stopped cleanly — usesome/everyto exit early.
Useful patterns
const unique = [...new Set(arr)];
const flat = nested.flat(2);
const chunks = Array.from({ length: Math.ceil(a.length / 10) }, (_, i) => a.slice(i * 10, i * 10 + 10));
const grouped = Object.groupBy(items, x => x.type); // modern runtimes
// shallow copy vs mutation
const sorted = [...nums].sort((a, b) => a - b); // keeps nums intactFAQ
How do I remove duplicates?
[...new Set(arr)] for primitives. For objects, reduce over a Map keyed by a unique property.map vs forEach?
map builds a new array — chainable and usually what you want. forEach is for side effects and returns undefined.Related
Objects and destructuring Functions and scope
Last refreshed 2026-09-17.