Array.flat()
The Array.flat
method flattens the elements of a nested array to a specific depth.
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.
The flat()
method removes empty values from an array.
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.
Let’s implement our own flattenMap method
. Let’s say we call our method flatten
. The steps to do this are:
flatten
methodvar 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]