Flatten An Array

Tuesday, February 14th 2023

Here is an example implementation for flattening a deeply nested array of arrays in JavaScript using the reduce() method:

javascriptCopy code

function flattenArray(arr) { return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []); }

In this implementation, the reduce() method is used to iterate over the elements of the input array arr. If the current value val is an array, the flattenArray() function is called recursively to flatten it, and the resulting array is concatenated to the accumulation acc using concat(). If val is not an array, it is simply concatenated to acc.

The initial value of the acc accumulation is an empty array []. This ensures that the final result will always be a flat array, regardless of the number of levels of nesting in the input array.