Flatten an array of arrays in JavaScript?

Answered
looper003 asked this question 4 months ago
looper003 on Jan 19

I have an array that contains other arrays, like this:

[["user41"], ["user9"], ["user22"], ["user54"], ["user71"], ["user10"], ["user11"], ["user28"], ["user73"]]

And convert it into a single level array:

["user41", "user9", "user22", "user54", "user71", "user10", "user11", "user28", "user73"]

How can I do this using JavaScript? I'm fine with using an external library if that's the best way to do this!

4 suggested answers
suparman21 on Jan 20

Lodash's flatten() method works nicely:

_.flatten(array)
0 replies
nick on Jan 20 · Edited
let flattened = [].concat.apply([], array)
0 replies
moon_man41 on Jan 20

You can use the Array.prototype.flat() method:

array.flat()

That will return a new array with the sub-array elements concatenated.

You can pass an optional depth parameter that determines how many depth levels it should flatten:

array.flat(3)

It is set to 1 by default.

0 replies
yaboy01 on Jan 20

This function will recursively flatten an array with n depth of nested arrays:

function flattenArray(array) {
  return array.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten)
  }, [])
}

You can use the function like this:

flattenArray([["user41"], ["user9"], ["user22"]]) // ["user41", "user9", "user22"]
flattenArray([[["user41"]], ["user22"], [[["user54"], ["user71"]], ["user10"]], ["user11"]]) // ["user41", "user22", "user54", "user71", "user10", "user11"]
0 replies
Answered