Explain Codes LogoExplain Codes Logo

Merge/flatten an array of arrays

javascript
prompt-engineering
functions
collections
Nikita BarsukovbyNikita Barsukov·Sep 12, 2024
TLDR

To normalize an array of arrays in JavaScript, apply the .flat() technique, an addition in ES2019:

let flatArray = [[1, 2], [3, 4]].flat(); // This leaves us with: [1, 2, 3, 4]

For flattening nested structures, indicate the required depth level:

let deepFlatArray = [[1, [2]], [3, [4]]].flat(2); // And voila: [1, 2, 3, 4]

In scenarios that do not support .flat(), use the .reduce() method along with .concat():

let flatArray = [[1, 2], [3, 4]].reduce((a, b) => a.concat(b), []); // This will return: [1, 2, 3, 4]

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.

let mixedArray = [[1, 'a'], [true, [2, 'b']]].flat(); // This will result in: [1, 'a', true, [2, 'b']]

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():

let legacyFlatArray = [].concat.apply([], [[1, 2], [3, 4]]); // Trust me, this works: [1, 2, 3, 4]

Infinity to the rescue

For arbitrarily nested arrays where the depth isn’t predictable, switch to .flat(Infinity)—Infinity War, anyone? 😉:

let veryNestedArray = [1, [2, [3, [4, [5]]]]]; let infiniteFlatArray = veryNestedArray.flat(Infinity); // Solved! Output: [1, 2, 3, 4, 5]

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:

let sparseArray = [1, , 3, , 5]; let compactedArray = sparseArray.flat(); // Awesome, right? Output: [1, 3, 5]

Double action with flatMap

flatMap() is a supplement to .flat() and .map(), permitting processing via a function and subsequently flattening the result:

let arrayOfArrays = [[1], [2], [3]]; let multipliedFlattened = arrayOfArrays.flatMap(arr => arr.map(num => num * 2)); // Double Trouble! Output: [2, 4, 6]

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:

require("core-js/features/array/flat"); let oldEnvArray = [[1, 2], [3, 4]].flat(); // Magical, isn't it? Output: [1, 2, 3, 4]

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.