A catalogue combines nested lists with flat, and the resulting list has fewer positions than expected. Another nested array remains visible even though the developer believed everything had been flattened. Neither result necessarily indicates lost records. The selected flattening depth and the treatment of absent indexed properties determine what the operation actually contributes to its output.
The short answer is that ordinary Array.prototype.flat descends into array elements only while its depth permits. At each array level it processes, it checks whether the indexed property exists before obtaining a value. Genuinely absent positions at those processed levels are omitted, while present undefined values remain values. Arrays left below the depth boundary are retained as array objects rather than recursively rewritten.
This guide uses original nested catalogue groups and explicit source ledgers. It concerns ordinary arrays with standard prototypes unless a case names a different condition. Flattening changes the shape of a representation; it does not establish that the original hierarchy was meaningless, validate every record or deeply copy every object that survives into the result.
This specialist guide belongs to the Websites root. It also connects to The Gold Standard of Education | Learning That Transfers into Life and the How X Works hub. The worked cases are original teaching examples; their numbers are stipulated so that the reasoning can be checked.
eduKateSG · Websites
Find your next learning step
Trace Array flat depth and sparse positions. Keep undefined entries, retained nested arrays, shared objects and source provenance distinct.
ROUTE 1 · CHAPTERS 1–3
Name the shape change
Work the outer hierarchy, default depth and deeper arrays left behind.
ROUTE 2 · CHAPTERS 4–6
Follow missing positions
Separate depth zero, explicit undefined and holes at processed levels.
ROUTE 3 · CHAPTERS 7–9
Inspect the returned structure
Trace a mixed catalogue, retained array-like records and shared object identities.
ROUTE 4 · CHAPTERS 10–12
Choose a bounded transformation
Compare flatMap, property effects and the limits of unrestricted descent.
ROUTE 5 · CHAPTERS 13–14
Check and explain
Verify original and changed-context fixtures, then preserve source meaning.
Chapter contents
Name the shape change · Chapters 1–3
1. Separate the outer list from the groups it contains
Follow missing positions · Chapters 4–6
4. Understand depth zero before calling it a plain copy
Inspect the returned structure · Chapters 7–9
7. Work a complete nested catalogue example
Choose a bounded transformation · Chapters 10–12
10. Follow flatMap as a one-level mapping contract
Check and explain · Chapters 13–14
CHAPTER 1 OF 14 · Name the shape change
1. Separate the outer list from the groups it contains
Begin with an outer array containing two group arrays. The first group holds catalogue labels Alder and Birch; the second holds Cedar. The outer array has length two, while the groups contain three labels in total. Neither count is wrong. They measure different levels of the hierarchy.
A request to combine the group labels into one sequence asks for a transformation of that hierarchy. Under ordinary one-level flattening, the output can be Alder, Birch and Cedar. The outer groups no longer occupy their own output positions as group arrays because the operation descended into them under its selected depth.
Write an original-path column beside an output-position column. Alder came from outer position zero, inner position zero, and becomes output position zero. Birch came from outer zero, inner one, and becomes output one. Cedar came from outer one, inner zero, and becomes output two. The flattened index is not the original group coordinate.
That coordinate change matters when a website later reports an error against the source form. Output position two identifies Cedar in the combined sequence, but it does not by itself preserve the source group's identity or the original field path. Retain that provenance separately when a reader needs to repair the originating entry.
The operation also does not decide whether combining the groups serves the product. A catalogue might need to preserve sections for accessibility, permissions or explanation. A flat sequence is appropriate only when its consumer needs that shape or retains the necessary grouping information elsewhere.
For the first transfer exercise, change the group sizes from two and one to one and three. Predict the outer length and output length separately, then map each label's original path to its new position. This establishes the representation boundary before missing positions and deeper nesting complicate the trace.
CHAPTER 2 OF 14 · Name the shape change
2. Work the default one-level transformation
Use the ordinary source [1, [2, 3], 4]. The default flat call has a depth of one. It retains the primitive one, descends into the array containing two and three, contributes those two values, and finally retains four. The ordinary result is a new array containing one, two, three and four.
The source is not thereby replaced with that result. Retain references to both objects and inspect them separately. The original outer array still has its inner array at position one. A helper that discards the return value has not requested an in-place structural replacement merely by calling flat.
The depth describes permitted descent through nested arrays, not the number of top-level positions to inspect. The operation examines the outer sequence under its length and property rules, while the depth determines what happens when an obtained element is itself an array. Conflating those two boundaries leads to incorrect predictions about later entries.
const source = [1, [2, 3], 4];
const result = source.flat();
// result: [1, 2, 3, 4]
// source still contains its nested array.
A returned primitive keeps its value in this example. A returned object introduces a separate identity question developed later. New output-array identity does not mean every contributed element was independently reconstructed. Keep structural flattening and copying depth as different claims from the beginning.
For a changed-context check, place an empty array between the groups. Descending into that empty array contributes no elements. The output does not gain an undefined marker merely because an outer group existed at that position. If the empty group has business meaning, such as a section with no eligible records, preserve that meaning explicitly rather than expecting flattening to invent a placeholder.
CHAPTER 3 OF 14 · Name the shape change
3. Put a second nesting level behind the boundary
Now use [1, [2, [3]], 4]. Default one-level flattening descends into the array at outer position one, contributes two and then encounters the array containing three with no remaining depth for another descent. That inner array remains an element of the output. The result is [1, 2, [3], 4].
The phrase flatten once can mislead a learner into imagining one single array is expanded and then the whole operation stops. Instead, the depth controls each eligible nested descent along the traversal. Other outer array elements can also be flattened by the same remaining-depth rule. The operation is not limited to the first nested array it finds.
Use a paper tree with a root for the outer sequence, one edge to the first group and another edge to the deeper array. Crossing the first edge consumes the permitted depth in this example. The next array is obtained as a value but not expanded. That explanation works even when labels and group sizes change.
With depth two, the ordinary operation can descend through both levels in this acyclic fixture and produce [1, 2, 3, 4]. The difference is the selected boundary, not a new ability to recognize arrays. A depth argument should express the desired representation rather than be increased until an unexplained output happens to look right.
A website importing a known schema can validate that schema and choose the corresponding transformation. An unpredictable depth may indicate mixed record kinds or an input-contract problem. Flattening more aggressively can conceal that problem by removing the very hierarchy needed to understand it.
For transfer, place a fourth nesting level under the second group and predict outputs at depths one and two. Name which array objects remain at the boundary. A complete answer identifies the surviving nested structure, not merely how many primitive labels eventually appear somewhere inside the result.
CHAPTER 4 OF 14 · Follow missing positions
4. Understand depth zero before calling it a plain copy
A flat call with depth zero does not descend into nested array elements. It can still create a new output array and process the outer positions under the flattening operation's property-presence rules. Calling it an exact structural copy of every outer slot would therefore be too strong for sparse inputs.
For a dense source containing one and a nested array of two, flat zero produces a new outer sequence containing those two elements. The nested array is retained as a value. Both the original and returned outer arrays can therefore refer to that same inner array in the ordinary fixture.
Now introduce an absent position in the outer source. Even with no permitted descent, the algorithm still checks outer property presence and skips the genuinely absent position. The returned array can be shorter and denser than the source. Zero depth does not switch off every transformation other than allocating a new object.
This is a useful contrast with a copy operation whose contract preserves a sparse structure. The right choice depends on what the caller intends to preserve: visible values, indexed-property layout, group boundaries or references. A method name associated with copying in another context cannot substitute for this operation's actual rules.
For an evidence record, retain source length, own indexed positions, selected depth, output length and output element identities. If the source has an inner array, test whether the result retains that inner reference. If it has missing outer positions, test whether those positions survive as missing positions or disappear.
For transfer, take a three-position outer array with a value at zero, a missing property at one and a nested array at two. Predict flat zero before execution. Then explicitly assign undefined at one and repeat. The different output lengths follow presence rather than depth, exposing two independent controls within the same call.
CHAPTER 5 OF 14 · Follow missing positions
5. Distinguish missing slots from undefined entries
A sparse array can have an index inside its length without an own indexed property there. Under the ordinary prototype assumptions used here, reading that missing position yields undefined. That read result does not mean the source already contained an explicit own entry storing undefined.
Flat's processing checks whether a property exists before obtaining its value at that source level. If the property is genuinely absent, it does not contribute an output element for it. If the property exists and its value is undefined, the value can be contributed like another non-array element.
Use a fresh three-position array with twelve at zero, a missing slot at one and explicit undefined at two. With flat zero, the ordinary result contains twelve followed by undefined and has length two. There is no output position reserved for the absent source property. The explicit undefined remains a present result entry.
This means output length is not generally the sum of source lengths when those lengths include holes at processed levels. The relevant contribution count depends on existing properties and permitted nested expansion. A calculation that treats each absent position as a contributed empty value will overcount the result.
The distinction also affects later operations. A consumer that assumes an output index equals the source index can associate a measurement with the wrong label after skipped positions compress the sequence. If missing observations must remain aligned, encode them explicitly or preserve source-path metadata rather than relying on a flattened positional correspondence.
For independent practice, swap which source position is missing and which explicitly stores undefined. The output can display the same sequence while the source paths differ. That is a concrete reason to retain provenance when explaining where a value came from; the flattened values alone need not recover the original sparse arrangement.
CHAPTER 6 OF 14 · Follow missing positions
6. Trace holes at processed and unprocessed levels
Construct an outer array with a missing first position and, at its second position, an inner array containing a missing position followed by the label Cedar. Default one-level flattening processes the outer missing position and skips it. It then descends into the inner array, skips that level's missing position and contributes Cedar.
The ordinary result is a one-element array containing Cedar. Two source levels had absent indexed properties, and both were processed within the selected depth. Neither absence becomes an undefined output entry merely because the corresponding array lengths included it.
Now place that sparse inner array one level deeper: the outer source contains an array whose first element is the sparse inner array. Default one-level flattening reaches the sparse inner array as a value at the depth boundary and retains it without descending into its positions. Its internal missing position remains part of that retained object's structure.
This is the boundary hidden by a statement such as flat removes all holes. It skips absent positions at the levels it actually processes. It does not recursively repair every array object reachable anywhere in the resulting value graph when the selected depth stops earlier.
For a precise trace, label levels rather than saying inner repeatedly. Outer level zero is always the initial source. The first nested descent reaches level one; another descent reaches level two. At each step record whether the operation is inspecting that array's indexed properties or merely contributing the array as an element.
For transfer, repeat the deeper fixture with depth two. The previously retained sparse array is now processed, its missing position is skipped and Cedar is contributed directly. Explain the changed output through a newly permitted descent, not through an imagined mutation of the sparse array that had been retained by the earlier call.
CHAPTER 7 OF 14 · Inspect the returned structure
7. Work a complete nested catalogue example
Here is a second explicit ledger with different labels. Let the source be [["Red", , "Blue"], , [["Gold", , "Silver"]]], using ordinary missing properties where the commas leave slots. At default depth, the first group contributes Red and Blue. The absent outer position contributes nothing. The final group contributes its one nested array as a retained value, so the output has three elements: Red, Blue and that sparse Gold–Silver array. The output's third element still has length three and an absent middle property.
At depth two, the operation processes that retained array as well. Gold and Silver become direct output values, and its absent middle property contributes nothing. The resulting sequence is Red, Blue, Gold, Silver with length four. None of the source arrays needed to be mutated to obtain either result. The two calls simply traversed to different depths and produced different outer representations.
Change the missing position between Gold and Silver to an explicit undefined entry. Default-depth output still retains the deeper array object, now with that present property. Depth-two output gains a direct undefined element between Gold and Silver. This changed-context calculation identifies which transformation first makes that property presence affect the flat result's length.
Create an outer sequence containing the label Header, a missing outer position, a group array with Alder and an explicit undefined, and another group containing a nested array with Cedar. The source has four outer positions, but only three existing outer entries. That outer description is the starting point of the ledger.
At default depth one, Header contributes one element. The absent outer position contributes none. The first group contributes Alder and undefined. The second group contributes its nested Cedar array as a retained array value because the permitted descent has already been used to enter that group.
The result therefore has four elements: Header, Alder, undefined and an array containing Cedar. Its length happens to equal the outer source length, but that numerical agreement conceals different structure. One missing outer position disappeared while one two-entry group expanded. Equal lengths do not prove positions were preserved.
With depth two, the nested Cedar array is also processed and Cedar becomes a direct element. This result still has four elements, now Header, Alder, undefined and Cedar. Again the count alone cannot distinguish the two outputs. Inspect element types and nesting, not only length.
Now delete the explicit undefined property from the first group while retaining that group's length. Default flattening skips that now-missing group position. The output shortens by one. Restoring an explicit undefined property restores the contribution. The changed count follows presence at a processed nested level, not a change in the outer sequence.
For independent transfer, replace the nested Cedar array with a non-array record containing a label field. Predict whether depth two expands that record. The answer depends on whether the obtained value is actually an array under the operation's test; having fields that look like a list does not automatically make a catalogue record eligible for flattening.
CHAPTER 8 OF 14 · Inspect the returned structure
8. Keep arrays distinct from array-like records
Ordinary flat can be borrowed for an array-like outer source under its generic contract. That does not mean every nested object with numeric properties and a length field is automatically expanded as an array element. The recursive flattening decision uses an actual array test for the obtained nested value.
Use an outer source containing one plain object with properties zero and length, where zero holds Alder and length is one. Under the ordinary fixture, flat retains that plain object as one result element. It does not replace it with Alder simply because a human can interpret the object as a one-entry list.
A typed array similarly has indexed data and a length but is not an ordinary Array under that recursive array test. In the central standard-object cases, placing a Uint8Array inside an outer Array does not ask flat to expand its bytes as though it were another nested Array. Choose an explicit transformation if that byte expansion is the intended job.
This boundary protects the explanation from overgeneralizing the word list. An application can use many sequence-like representations: ordinary arrays, typed arrays, DOM collections and custom records. Similar-looking iteration interfaces do not establish identical behaviour under every array method.
For a changed-context fixture, replace the plain array-like record with a true ordinary array containing Alder. Keep the apparent single value the same and call flat again. The new result can contain Alder directly because the nested value now satisfies the relevant array condition. Record that representation change beside the result.
A programmer should therefore define the accepted nested schema before flattening. If arbitrary objects can appear, validate or deliberately convert the supported kinds rather than relying on flat to infer the author's intention. A mechanically valid retained record may still violate the shape the consuming catalogue view expects.
CHAPTER 9 OF 14 · Inspect the returned structure
9. Separate new outer identity from deep isolation
Flat normally returns a new result array in the ordinary built-in cases described here. That new outer identity does not promise an independent copy of each contributed object. A catalogue record that survives as an element can still be shared between source and result.
Create a plain record with label Alder and place it inside a group array. Flatten the outer group sequence by one level. The returned first element refers to that record. If its label later changes to Birch through the retained reference, reading the result's element can show Birch too. No new flat call was needed for that shared-object observation.
Replacing a source array's entry with a different record is another operation. The already produced result can still refer to the earlier record rather than follow the source association automatically. Shared object identity and live lookup through a source index are different relationships.
The same distinction applies to an array retained at the depth boundary. The result can contain that same inner array object. Mutating it through one reference can be visible through the other, while replacing the original parent's reference does not automatically redirect the already returned result element.
This is why a report saying the data was copied needs a stated preservation target. New outer sequence, copied primitive values, retained nested arrays and shared record objects describe different aspects of the output. The structured-cloning and object-copying specialists explain other contracts; they should not be silently substituted for flattening.
For transfer, perform both a field mutation on the retained record and a later replacement of the source entry. Predict the output after each. The learner should identify which object the result actually holds, rather than crediting every visible change to an unspecified live-array mechanism or every unchanged value to a deep snapshot guarantee.
CHAPTER 10 OF 14 · Choose a bounded transformation
10. Follow flatMap as a one-level mapping contract
For a numeric check, start with two and three. Define the callback to return [2,20] for the first value and an empty array for the second. The result is [2,20], not an array containing two group arrays and not a three-position sequence with a blank placeholder for three. The missing contribution follows the callback’s deliberate empty-array return. If the second callback instead returns undefined, the result gains a present undefined element. Changing a callback return therefore changes output meaning even when the source and visitation count remain identical.
FlatMap combines a mapping callback with a one-level flattening operation on the mapped values under its ordinary contract. It is not a request to flatten every nested structure the callback can return to arbitrary depth. The callback's result shape therefore matters as much as the source shape.
Use a dense source containing two catalogue codes. Let the callback return a two-label array for the first code and an empty array for the second. The first mapped array contributes two result elements; the empty array contributes none. This can express an intentional one-to-many transformation or omission policy when the application defines it clearly.
Now make the callback return an array containing another array for the first code. One level of flattening leaves that deeper array as a result element. Returning a plain record instead of an array contributes that record as one element. The mechanism follows the actual mapped value, not a guessed desired output type.
The callback is invoked for source positions that the ordinary algorithm actually visits under its property-presence check. A missing source position is not simply passed to the callback as an explicit undefined value in this contract. A present source position containing undefined can be visited and can lead to a deliberate mapped result.
Do not claim this combination validates or deduplicates records automatically. A callback returning repeated labels can produce repeated labels. A callback returning invalid records can preserve those invalid records. Mapping and one-level structural expansion are operations whose outputs still need to satisfy the consuming schema.
For an independent exercise, use one missing source position, one explicit undefined entry and one ordinary label. Have the callback record its index and return a pair of markers for each visited entry. Predict the callback indices and output length. This connects source presence with mapped shape without borrowing the different iterator-consumption contract developed in the Array.from specialist.
CHAPTER 11 OF 14 · Choose a bounded transformation
11. Treat property reads and failures as observable work
Ordinary flat obtains the values of eligible source properties as it proceeds. A deliberately defined accessor can therefore run when its position is reached. A getter can return a nested array, change another property or throw. A result-array transformation is not a guarantee that the source object had no observable behaviour.
Use an isolated ordinary array with a getter at position zero that records a marker and returns Alder. Place a second getter at one that throws. Calling flat can record the first marker before the second access prevents normal completion. No returned result does not imply no earlier getter ran.
Keep these fixtures separate from the plain-data catalogue examples. The earlier examples assume stable ordinary indexed data. Introducing getters changes the conditions under which later values are obtained, and the report should identify that change rather than presenting the result as a contradiction of the baseline trace.
Source lengths are obtained at particular processing boundaries. A callback or getter changing an array during processing can require a more detailed trace of which length was captured and which later properties are checked. Do not infer a universal immutable snapshot from an initial length, nor assume every new index will necessarily be visited.
The practical repair is to choose an accepted representation and a bounded inspection plan. If the input must be inert validated records, establish that contract before flattening. If arbitrary accessors are permitted, retain their possible effects and error outcomes in the application's handling policy.
For transfer, compare three cases: a getter returning a primitive, a getter returning an array and a getter throwing after an earlier marker. Predict contribution, descent and completion separately. This distinguishes the value obtained from the existence check that made its read eligible and from the later decision to expand it.
CHAPTER 12 OF 14 · Choose a bounded transformation
12. Put limits on unrestricted flattening
A depth of Infinity permits continued descent through nested arrays in ordinary acyclic examples until no further array nesting remains. It is not a proof that an arbitrary value graph can be flattened safely, quickly or completely. Finite input size, cyclic references and implementation resource limits still matter.
A self-referential array can contain itself as an element. Unrestricted recursive flattening of that structure does not describe a finite list of leaf records under the simple tree model used earlier. Do not demonstrate the problem by running an unbounded or resource-exhausting operation inside a reader's page.
The safe teaching fixture states acyclicity and uses a small finite depth. If the real importer accepts arbitrary graphs, it needs an explicit cycle and resource policy appropriate to that contract. Raising a depth argument until a particular example disappears is not such a policy.
Even a finite hierarchy can be large enough that expanding every leaf is inappropriate for the next screen. A catalogue view may need pagination, preserved grouping or a bounded preview. Flat does not decide those reader-facing limits, and the lesson makes no benchmark claim about its performance on an unmeasured production dataset.
For a concrete planning exercise, stipulate five groups with four records each and ask whether the consumer needs all twenty records or only one group's records. Count the expected contributions before choosing a transformation. A full flattening operation may be correct for one requirement and unnecessary for another.
For transfer, replace the known two-level schema with an unknown external structure. The correct first move is to recover its accepted shape and limits, not immediately apply Infinity. The durable skill is specifying which hierarchy may be removed and which information must survive, then checking that the chosen operation respects those boundaries.
CHAPTER 13 OF 14 · Check and explain
13. Verify the representation with bounded fixtures
The controlled checks begin with dense one-level and two-level sources. Assert the exact output sequence at default depth, depth zero and depth two. Retain the source and result identities and verify that calling the operation did not replace the source's own outer structure.
Add an outer sparse source with explicit undefined and a missing property. Assert source length, source presence, result length and result presence. Then use a sparse array retained below the depth boundary and repeat with a larger permitted depth. These checks expose the precise scope of omitted positions.
Check a plain array-like nested record and a typed array as retained values, then replace each with a true ordinary Array. The output change should follow the representation test described in the lesson. The assertions must inspect element identity and type, not just the printed words that happen to appear inside it.
Use a shared catalogue object to check field mutation versus source-entry replacement after flattening. For flatMap, record callback indices for a sparse source and compare primitive, empty-array and nested-array returns. Keep these cases finite, fresh and separate so earlier mutations cannot alter later baselines.
Finally verify a counted getter and an intentional throw. Preserve the marker observed before failure. These are controlled language observations in a recorded runtime, without network requests, real imports or a browser catalogue deployment. They establish the stated fixtures and their limits.
For a real website, inspect the accepted input schema, depth choice, missing-data meaning, source-path retention and consumer expectations. The small fixtures provide precise questions for that review. They do not certify an entire import pipeline merely because the final array looks visually simpler.
CHAPTER 14 OF 14 · Check and explain
14. Preserve the reader's meaning while changing shape
A useful report states the original hierarchy, selected depth, relevant property-presence assumptions and resulting sequence. It names any arrays retained at the depth boundary and any record identities shared with the source. Output length alone cannot communicate those facts.
When a position disappears, ask whether it was genuinely absent at a processed level, an empty array that contributed no elements or a mapped value deliberately replaced with an empty array. Those are different mechanisms. An explicit undefined value is another case and should not be described as an omitted hole merely because it looks blank.
When a nested array remains, locate the depth boundary before changing the argument. A surviving array may be the intended representation. If the consumer requires a flat record list, validate that expectation and the source schema rather than treating every nested value as a formatting accident.
For catalogue feedback, retain source paths where needed. An error at output position three cannot necessarily be sent back to source position three after structural expansion and omission. The transformation should preserve enough context for a learner or developer to repair the original record accurately.
The final changed-context exercise asks for a dense group, an empty group, a missing outer position and one deeper sparse array. Predict two different depths and explain both outputs through contributions at each level. Then state what provenance the consuming interface needs. This tests understanding beyond memorizing one flattened list.
The lasting habit is to name what flattening is allowed to remove. Group boundaries, absent positions, object identities and input meaning are separate concerns. Once those concerns are explicit, the author can simplify a representation while retaining the information the website and its readers actually need.
Continue through the verified reading route
Tracing Default Array Sort Order Through Numbers, Undefined Values and Empty Slots
Tracing Default Array Sort Order Through Numbers, Undefined Values and Empty Slots. Compare missing positions and undefined under sorting before assuming every array transformation visits the same entries.
Tracing Array.from Mapping Before Source Consumption Finishes
Tracing Array.from Mapping Before Source Consumption Finishes. Distinguish iterable materialisation and interleaved mapping from the flatMap contract in this lesson.
Tracing toJSON Conversion Before Replacer Decisions
Tracing toJSON Conversion Before Replacer Decisions. Check another representation-changing operation: JSON conversion can change what later processing receives.
Search membership after changing an array’s shape. Compare the presence and equality rules used by includes and indexOf on the resulting representation.
Initialize a reduction over the actual sparse source. Check whether a value supplied the seed or reached the callback, rather than assuming all array methods visit identically.
Compare flattening with concat’s item boundary
Separate concat spreadability from iterable expansion. A nested parcel, a sparse indexed source and a custom iterator can supply different shapes; trace the selected interface before choosing a sequence operation.
Compare Array flattening with inner iterator traversal
Trace Iterator.flatMap inner consumption. Compare sparse positions, accepted mapped representations and lazy group coverage with this article’s indexed Array flattening contract.
Frequently asked questions
Does flat change the original outer array?
In these ordinary built-in fixtures it returns a new outer array. Elements and retained nested objects can still be shared references.
Does depth zero preserve every sparse slot?
No. It prevents nested descent, but absent positions at the processed outer level are still omitted.
Is undefined removed like a hole?
A present undefined entry contributes a value. A genuinely absent property at a processed level contributes no element.
Will every array-like object be flattened?
No. The recursive decision tests for an array. A nested plain array-like record is not automatically expanded as an ordinary Array.
Does flatMap flatten everything returned by its callback?
Its ordinary contract supplies one level of flattening. A deeper nested array can remain an output element.
Should I always use Infinity?
Choose the depth from the accepted schema and task. Arbitrary cyclic or very large structures need explicit limits and handling beyond the small acyclic examples here.
Authoritative sources and further reading
ECMAScript: Array flat. Depth conversion and the ordinary flattening entry point.
ECMAScript: FlattenIntoArray. The property-presence check, array test and recursive contribution rules.
ECMAScript: Array flatMap. The mapping callback combined with one-level flattening.
Return to the Websites subject guide, The Gold Standard of Education, or the How X Works hub.