Merge/flatten an array of arrays
To normalize an array of arrays in JavaScript, apply the .flat()
technique, an addition in ES2019:
For flattening nested structures, indicate the required depth level:
In scenarios that do not support .flat()
, use the .reduce()
method along with .concat()
:
Use-cases and coding hacks
Mixed content arrays - one function to sort them all
In the event you are dealing with arrays holding diverse data types, including nested arrays, just use .flat()
with a proper depth to flatten the array robustly, concurrently maintaining data integrity of each element.
Ensuring legacy browser compatibility
When programmatically targeting archaic browsers like Internet Explorer that do not support .flat()
, resort to the good old .concat()
and .apply()
:
Infinity to the rescue
For arbitrarily nested arrays where the depth isn’t predictable, switch to .flat(Infinity)
—Infinity War, anyone? 😉:
Pro tips for JavaScript ninjas
In search of the missing elements
With sparse arrays where empty slots are present, .flat()
can be utilized to dispose of these vacant slots:
Double action with flatMap
flatMap()
is a supplement to .flat()
and .map()
, permitting processing via a function and subsequently flattening the result:
When to polyfill like a pro
Engage in polyfilling .flat()
in instances where it's unavailable by employing a package, consider core-js@3
, which includes the flat()
function:
Expert Practices
Always verify the environment compatibility for .flat()
, and have a fallback in place such as .concat()
with .apply()
or a custom function using .reduce()
and .concat()
when targeting older platforms.
Was this article helpful?