Flatten Nested Arrays
flat reduces the nesting level of arrays.
By default it flattens one level.
JavaScript Tutorial
flat reduces nested arrays into a single level array.
It is useful for cleaning nested data.
Nested arrays appear in grouped data, UI grids, and API responses.
flat makes that data easier to process.
array.flat(depth)const nested = [1, [2, 3]];
const flat = nested.flat();
console.log(flat);Default depth is 1.
const nested = [1, [2, [3]]];
const flat = nested.flat(2);
console.log(flat);Provide depth to flatten further.
flat reduces the nesting level of arrays.
By default it flattens one level.
Pass a depth number to flatten deeper levels.
Use Infinity to fully flatten.
flat returns a new array and does not mutate the original.
That makes it safe for immutable workflows.
Without
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);With
const flat = nested.flat();flat returns a new array.
Specify depth when arrays are deeply nested.
flat only works on arrays.
It flattens nested arrays to a given depth.
No, it returns a new array.
Use flat(Infinity).
Practice: Flatten a two-level nested array.
const nested = [1, [2, 3]];
// TODO: flatten
One Possible Solution
const nested = [1, [2, 3]];
const flat = nested.flat();
console.log(flat);No, it returns a new array.
1.
Use flat(Infinity).
Try different depths to see how arrays flatten.