Iteration methods call your function once per element with (element, index, array). They do not mutate the array themselves, and chaining filter(), map() and reduce() turns most hand-written loops into a readable pipeline.
| Method | Returns | Mutates? |
|---|---|---|
| keys(), values(), entries() | Iterator (Iterables and Iterators) | No |
| map(fn), filter(fn) | New array | No |
| reduce(fn, init) | One accumulated value | No |
| some(fn), every(fn) | Boolean; stops early | No |
| find(), findIndex() | First match or its index | No |
| flat(depth), flatMap(fn) | New flattened array | No |
const orders = [
{ id: 1, total: 30, items: ['pen', 'ink'] },
{ id: 2, total: 120, items: ['desk'] },
{ id: 3, total: 75, items: ['lamp'] },
];
const big = orders.filter((o) => o.total > 50).map((o) => o.id);
const revenue = orders.reduce((sum, o) => sum + o.total, 0);
console.log(big, revenue, orders.flatMap((o) => o.items));
console.log(orders.some((o) => o.total > 100), orders.findLast((o) => o.total > 50).id);
for (const [i, { id }] of orders.entries()) if (id > 1) console.log(i, id);[ 2, 3 ] 225 [ 'pen', 'ink', 'desk', 'lamp' ] true 3 1 2 2 3
reduceRight(), findLast() and findLastIndex() work from the end. Pitfalls:
Give reduce() an initial value; on an empty array without one it throws TypeError.
['1', '2', '3'].map(parseInt) gives [1, NaN, NaN], because the index arrives as the radix.
forEach() cannot break; use some(), find() or for...of. For huge or endless data, the lazy iterator helpers (arr.values().filter(f).map(g), Iterator Helpers) avoid building intermediate arrays.