map and reduce are loops covered in their own answers (map keeps holes; reduce throws on an empty array without an initial value). flat(depth = 1) walks the array and, when an element is an array and depth remains, walks into it with depth - 1; otherwise it adds the element. concat returns a new array: the original's elements, then each argument, spreading arrays one level and adding anything else as one element. The spec details interviewers check: flat drops holes but concat keeps them, flat accepts odd depths (Infinity, NaN as 0), concat honours Symbol.isConcatSpreadable, and a stack-based flat survives very deep nesting.
Implement Array.prototype methods (flat, map, reduce, concat) by yourself using JavaScript.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
flat is a reduce that recurses into arrays while depth > 0, so flat(Infinity) flattens everything. concat copies the original, then spreads each array argument one level and pushes everything else. Both return new arrays and leave the original alone. (map and reduce have their own answers.)
// One level by default; recurse while depth remains.Array.prototype.myFlat = function (depth = 1) {return this.reduce((out, item) => {if (Array.isArray(item) && depth > 0) out.push(...item.myFlat(depth - 1));else out.push(item);return out;}, []);};// Arrays are spread one level; anything else is added as one element. The original isn't changed.Array.prototype.myConcat = function (...items) {const out = [...this];for (const item of items) {if (Array.isArray(item)) out.push(...item);else out.push(item);}return out;};
passes 3 checks run on every build, against the native method where there is one
- flat: one level by default, deeper on request, like native
- concat spreads arrays one level and keeps the rest
- both return new arrays
The spec's flat skips missing indexes (k in source), so holes vanish at every level it flattens. Depth goes through ToIntegerOrInfinity: NaN and null mean 0, fractions are cut, strings are converted. concat is different: it keeps holes in spread arrays and decides what to spread with Symbol.isConcatSpreadable (an array-like can opt in; an array can opt out), falling back to Array.isArray.
function toLength(value) {const n = Math.trunc(Number(value)) || 0;return Math.min(Math.max(n, 0), Number.MAX_SAFE_INTEGER);}// The spec's ToIntegerOrInfinity: NaN is 0, fractions are cut, Infinity stays.function toIntegerOrInfinity(v) {const n = Number(v);if (Number.isNaN(n) || n === 0) return 0;return Number.isFinite(n) ? Math.trunc(n) : n;}Array.prototype.myFlat = function (depth) {const d = depth === undefined ? 1 : toIntegerOrInfinity(depth);const out = [];const visit = (source, level) => {const len = toLength(source.length);for (let k = 0; k < len; k++) {if (!(k in source)) continue; // holes are dropped, at every level that gets flattenedconst item = source[k];if (level > 0 && Array.isArray(item)) visit(item, level - 1);else out.push(item);}};visit(Object(this), d);return out;};// Spread arrays, or anything that opts in with Symbol.isConcatSpreadable. Unlike flat, concat keeps// holes in the arrays it spreads.Array.prototype.myConcat = function (...items) {const spreadable = (v) => {if (v === null || (typeof v !== 'object' && typeof v !== 'function')) return false;const flag = v[Symbol.isConcatSpreadable];return flag !== undefined ? Boolean(flag) : Array.isArray(v);};const out = [];let n = 0;for (const item of [Object(this), ...items]) {if (spreadable(item)) {const len = toLength(item.length);for (let k = 0; k < len; k++, n++) if (k in item) out[n] = item[k];} else out[n++] = item;}out.length = n; // trailing holes still countreturn out;};
passes 5 checks run on every build, against the native method where there is one
- flat drops holes at flattened levels, like native
- odd depths: 0, negative, NaN, fractions, strings
- concat keeps holes, like native
- Symbol.isConcatSpreadable opts in or out
- array-likes without the symbol are not spread
Recursion depth equals nesting depth, so flat(Infinity) on 100,000 levels overflows. An explicit stack of frames (array, next index, depth left) gives the same order with no recursion. flatMap is map followed by flat(1) in one pass: only arrays the callback returns are spread, which makes it the tool for map-and-filter in one step (return [] to drop an item). The first check compares with native flat on 200 random nestings.
function toLength(value) {const n = Math.trunc(Number(value)) || 0;return Math.min(Math.max(n, 0), Number.MAX_SAFE_INTEGER);}function toIntegerOrInfinity(v) {const n = Number(v);if (Number.isNaN(n) || n === 0) return 0;return Number.isFinite(n) ? Math.trunc(n) : n;}// flat without recursion: an explicit stack of [array, next index, depth left], so a 100,000-deep// nesting can't overflow the call stack. Order is the same as the recursive walk.Array.prototype.myFlat = function (depth) {const d = depth === undefined ? 1 : toIntegerOrInfinity(depth);const out = [];const stack = [[Object(this), 0, d]];while (stack.length) {const frame = stack[stack.length - 1];const [source, , level] = frame;if (frame[1] >= toLength(source.length)) {stack.pop();continue;}const k = frame[1]++;if (!(k in source)) continue;const item = source[k];if (level > 0 && Array.isArray(item)) stack.push([item, 0, level - 1]);else out.push(item);}return out;};// flatMap is map then flat(1), in one pass. Only arrays returned by the callback are spread.Array.prototype.myFlatMap = function (callback, thisArg) {if (typeof callback !== 'function') throw new TypeError(`${String(callback)} is not a function`);const O = Object(this);const len = toLength(O.length);const out = [];for (let k = 0; k < len; k++) {if (!(k in O)) continue;const mapped = callback.call(thisArg, O[k], k, O);if (Array.isArray(mapped)) {for (let j = 0; j < mapped.length; j++) if (j in mapped) out.push(mapped[j]);} else out.push(mapped);}return out;};
passes 4 checks run on every build, against the native method where there is one
- matches native flat on 200 random nestings
- a 100,000-deep nesting doesn't overflow
- flatMap spreads one level of returned arrays, like native
- flatMap passes index, array and thisArg; skips holes
Flattening paginated results
Fetching pages of results gives an array of arrays: pages.flat() (or pages.flatMap((p) => p.items)) turns them into one list.
Map and filter in one pass
flatMap lets a callback return zero, one or many items: users.flatMap((u) => (u.active ? [u.email] : [])) maps and filters at once.
Why it's called flat, not flatten
The proposal was flatten until it turned out MooTools, an old library still on many sites, had already put a different Array.prototype.flatten there; shipping the standard one would have broken those sites. It was renamed flat.
concatwith a nested array expecting deep flattening: it spreads only one level.Recursion in
flat(Infinity)on untrusted, deeply nested data.Assuming
flatkeeps holes (it drops them) or thatconcatdrops them (it keeps them).Mutating the original array: both methods return a new one.
[].concat(...arrays)on a huge list of arrays: spreading thousands of arguments can exceed the engine's argument limit; usearrays.flat().
How would you flatten without recursion or a stack?
Loop while any element is an array: while (xs.some(Array.isArray)) xs = [].concat(...xs). It's simple but O(n·d), re-scanning the whole array once per level.
What does Symbol.isConcatSpreadable let you do?
Make an array-like (such as arguments or a custom collection) spread in concat, or stop an array from spreading, by setting the symbol to true or false on the object.
Does flat flatten array-likes like NodeList?
No: it checks Array.isArray, so only real arrays are flattened. Convert with Array.from first.
- tc39.es/ecma262/#sec-array.prototype.flat
- tc39.es/ecma262/#sec-array.prototype.flatmap
- tc39.es/ecma262/#sec-array.prototype.concat
- tc39.es/ecma262/#sec-isconcatspreadable
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/isConcatSpreadable