Array Flat Method
flat() returns a new array in which nested arrays are replaced by their elements. By default it removes one level of nesting, which suits the common case of an array of lists that should be one list.
const weeks = [[3, 5], [2], [4, 6, 1]];
console.log(weeks.flat());This prints:
[ 3, 5, 2, 4, 6, 1 ]The original array is not changed.
Choosing the depth
Section titled “Choosing the depth”An optional argument says how many levels to flatten. Pass Infinity to flatten every level, however deep the nesting goes.
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat());console.log(nested.flat(2));console.log(nested.flat(Infinity));This prints:
[ 1, 2, [ 3, [ 4 ] ] ][ 1, 2, 3, [ 4 ] ][ 1, 2, 3, 4 ]Empty slots are removed
Section titled “Empty slots are removed”A sparse array has empty slots, written as a gap between commas. flat() drops those slots, at the top level and inside the arrays it flattens. Real values such as null and undefined are kept, because they are elements rather than gaps.
const sparse = [1, , 3, [4, , 6], null, undefined];
console.log(sparse.flat());This prints:
[ 1, 3, 4, 6, null, undefined ]Steve Griffith covers this topic in his video Using the Array flat method.