Arrays #2 — flat, flatMap, find, every, some Polyfills

Implement Array.prototype.flat with depth, flatMap, find, findIndex, every, and some — with sparse array handling and edge cases.

11 min read
JavaScript
Arrays
Polyfill

TABLE OF CONTENTS
Arrays #2 — flat, flatMap, find, every, some Polyfills

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 — Infinity flattens everything, sparse slots are removed.
  • flatMap is map + flat(1) in one pass — use when your map returns arrays.
  • find/findIndex return on the first match — undefined/-1 if none.
  • every short-circuits on false; some short-circuits on true.
  • forEach is for side effects — it always returns undefined.
  • All methods skip empty slots via the i in this check.

Next: Arrays #3 — Array Methods Usage Reference — every array method organized by purpose with runnable examples for all 30+ methods.


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI