Flattening Arrays in Javascript Recursively

January 16, 2019

In many cases when processing data you would need to flatten the final result, specially when using promises and resolving multiple pieces of data separately.

Here's a recursive and efficient way of flattening an array:

// Function to flatten arrays
const arrayFlatten = arr => (
    arr.reduce((accum, currentItem) => {
        const flattenedItem = Array.isArray(currentItem) ? arrayFlatten(currentItem) : currentItem

        return accum.concat(flattenedItem)
    }, [])
)

// Test your function
const data = [
    [1, 32, 52],
    [325, 2132, 352],
    [91, 732, 652]
]

console.log(arrayFlatten(data))