Building on map, filter, and reduce, this article implements flat, flatMap, find, findIndex, every, and some — the remaining essential array methods — from scratch.
1. Implementing Array.prototype.flat(depth)
flat recursively flattens nested arrays up to a specified depth (default 1, Infinity for complete flattening):
Loading editor...
2. Implementing Array.prototype.flatMap()
flatMap is map followed by flat(1) — but more efficient because it's done in one pass:
Loading editor...
3. Implementing Array.prototype.find() and findIndex()
find returns the first element that passes the test; findIndex returns its index:
Loading editor...
4. Implementing Array.prototype.every() and some()
every checks if ALL elements pass the test. some checks if AT LEAST ONE passes. Both short-circuit:
Loading editor...
5. Implementing Array.prototype.forEach()
forEach is like map but returns undefined — it's for side effects, not transformation:
Loading editor...
6. Quick Reference — All Array Methods
Loading editor...
Key Takeaways
flat(depth)recursively flattens —Infinityflattens everything, sparse slots are removed.flatMapismap+flat(1)in one pass — use when your map returns arrays.find/findIndexreturn on the first match —undefined/-1if none.everyshort-circuits onfalse;someshort-circuits ontrue.forEachis for side effects — it always returnsundefined.- All methods skip empty slots via the
i in thischeck.
Next: Arrays #3 — Array Methods Usage Reference — every array method organized by purpose with runnable examples for all 30+ methods.
