Array Flatten in JavaScript
What are Nested Arrays?
A nested array is an array inside another array.
Eg. const arr = [b, c, [a, e, i, o, u], d, [f, g]]
Why flattening arrays is useful?
Flattening of arrays in JavaScript involves merging multiple nested arrays into a single array. It helps with easier data processing and simplifies operations.
Flattening = removing all layers of nesting
Different approaches to flatten arrays
- We use array.flat() method primarily to flatten an array. This creates a new array with all the sub elements concatenated to it.
Eg. let arr = [10, [20, 30], [40, [50, 60]], 70]
let flatArr = arr.flat(Infinity);
console.log(flatArr);
Output: [10, 20, 30, 40, 50, 60, 70]
- Using recursion, which means repeating the same process for nested arrays until everything has been flattened.
Eg. function flattenArray(arr){
let result = []
function flatten(elem){
if (Array.isArray(elem)){
for (let i =0; i < elem. length; i++){
flatten(elem[i]);
}} else {
result.push(elem)
}}
flatten(arr)
return result
}
if the element turns out to be array then recurse else push.
- Using reduce
Eg. function flatten(arr){
return arr.reduce((acc, curr) => {
return acc.concat(
Array.isArray(curr) ? flatten(curr) : curr
)
}, [])
}
