JavaScript Array flat
Method (Live Playground)
The JavaScript Array flat
method is used to flatten an array, which means it converts a multi-dimensional array into a single-dimensional array.
Here's a basic example of how you can use the flat
method:
let nestedArray = [1, [2, 3], [4, [5, 6]]];
let flattenedArray = nestedArray.flat();
console.log(flattenedArray);
// Expected output:
// [1, 2, 3, 4, [5, 6]]
In the example above, nestedArray.flat()
creates a new array that's one level less nested than the original. The default depth that flat
flattens is 1.
Live Playground, Try it Yourself
You can also specify the depth to which you want to flatten the array:
let deeplyNestedArray = [1, [2, [3, [4, [5]]]]];
let deeplyFlattenedArray = deeplyNestedArray.flat(4);
console.log(deeplyFlattenedArray);
// Expected output:
// [1, 2, 3, 4, 5]
In this second example, deeplyNestedArray.flat(4)
flattens the array to 4 levels deep, resulting in a completely flattened array.
Live Playground, Try it Yourself
Using the flat
method can simplify your code when you're working with nested arrays in JavaScript.