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
MethodReturnsMutates?
map/filter/slice/concatnew arrayNo
push/pop/shift/unshiftlength/elementYes
spliceremoved itemsYes
sort/reversethe array itselfYes
reduceanythingDepends 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 surprises
  • for…of for values, supports break/await.
  • for…in enumerates keys and is meant for plain objects.
  • forEach cannot be stopped cleanly — use some/every to 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 intact

FAQ

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.

Objects and destructuring Functions and scope

Last refreshed 2026-09-17.