What is the Array.flat() method in JavaScript?

Array.flat()

The Array.flat method flattens the elements of a nested array to a specific depth.

Console

The flat() method creates a new array that has all the sub-array elements recursively concatenated into it up to a specified depth. The default depth is 1.


Console

Removes Empty Values

The flat() method removes empty values from an array.

Console

Flattens all levels

If we don’t know how nested the array is, but we need to flatten all levels of an array, pass Infinity as the depth. It will flatten all levels of the array.

Console

Custom Flattening Function

Let’s implement our own flattenMap method. Let’s say we call our method flatten. The steps to do this are:

  • Loop through each element of the array
    • Check if the element is an array
    • If it is an array, call the flatten method
    • If it is not an array, append to the resulting array
var arr = [[2], [[2]], [1,2,[3,4,[5,6]]] ];
function flatten(arr) {
let flattenArray = [];
for(let i = 0, l = arr.length; i < l; i++){
let val = arr[i];
if(Array.isArray(val)) {
flattenArray.push(...flatten(val));
} else {
flattenArray.push(val);
}
}
return flattenArray;
}
console.log("Before flattening", arr);
console.log("After flattening", flatten(arr)); // [2 , 2, 1, 2, 3, 4, 5, 6]

Free Resources