Iteration Methods

Prototype Methods: Iteration

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.

Iteration methods of Array.prototype
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
A filter-map-reduce pipeline over order dataJavaScriptLive
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);

reduceRight(), findLast() and findLastIndex() work from the end. Pitfalls: