DEV Community

cortim
cortim

Posted on

Quick Tip: Flattening a multidimensional array

Array with one level of nesting:
const arr = [[1, 2, 3], ["foo", "bar"], [4, "baz"]]

To make it flat:
const flatten = arr.flat() // [1, 2, 3, "foo", "bar", 4, "baz"]

Here, we're using the flat(depth) method, where depth defaults to 1. Therefore, flat() is equivalent to flat(1).
We can flatten arrays with as many levels of nesting as needed. If unsure about the number of levels, we can always use flat(Infinity), which will flatten all nested arrays.

Top comments (0)