Flatten Array in JavaScript
why do it need to flatten array and various ways of flatten the array

This blog is all about flatten the array in JavaScript. The concept of flatten the array and explained various ways for flatten the array with some common interview questions .
What is Flatten means ?
Flatten array means converting nested arrays of many dept to single level array
Why we need to do that ?
Generally The developer who works in frontend need to show data which is coming from api to UI so . They prefer to come response in easy data structure as much as possible. when there is single level array then there are more easy to process data
Looping through data becomes easy
Easier to apply array methods like map, filter
Easier to get required data from array and show on UI
performance wise also single level array is good
Examples
const arr = [1, 2, [34, 10], [7, 9, [100]]];
console.log(arr); //[ 1, 2, [ 34, 10 ], [ 7, 9, [ 100 ] ] ]
console.log(arr.flat(Infinity)); // to flatten to more depth
// [ 1, 2, 34, 10, 7, 9, 100 ]
Different ways to flatten array
1 . using built in flat method
we can directly use flat array methods. It accepts depth of nested to give flatten output.
const alphas = ["a", "b", ["c"], ["d", ["e", ["f", ["g"]]]]];
console.log(alphas.flat(1)); // one level
console.log(alphas.flat(2)); // 2 level depth
console.log(alphas.flat(4)); // 4 level depth
/**
* [ "a", "b", "c", "d", [ "e", [ "f", [ "g" ] ] ] ]
[ "a", "b", "c", "d", "e", [ "f", [ "g" ] ] ]
[ "a", "b", "c", "d", "e", "f", "g" ]
*/
2 . using recursion
This is asked in interview . Just use recursion function to flatten array
// using recursion
const flatten = (arr) => {
return arr.reduce((acc, arr) => {
return acc.concat(Array.isArray(arr) ? flatten(arr) : arr);
}, []);
};
console.log(flatten(alphas));
// [ "a", "b", "c", "d", "e", "f", "g" ]
3 . using flatMap
it does two works flat + map . it only flatten array to one level
const result = [1, 2, [3, 4], [5, 6]].flatMap((i) => i);
console.log(result);
// [ 1, 2, 3, 4, 5, 6 ]
4 . using loop and spread
const flatResult = [];
for (let el of nums) {
if (Array.isArray(el)) {
flatResult.push(...el);
} else {
flatResult.push(el);
}
}
console.log(flatResult);
Common Interview Questions
1 . Flat deeply nested array without flat()
using recursion
2 . Flatten array with unknown depth
use Infinity depth
array.flat(Infinity)
3 . Flatten and remove falsy values
arr.flat(Infinity).filter(Boolean)
Diagram showing recursion of flatten array
Summary
Flatten is process of converting the nested array of many depth into the one level or any required depth. There are different ways of doing flattening the array in JavaScript.
There is built in array method flat method which do shallow or deep flatten according to depth provide to it.
without using built in methods we can flatten the array by using recursive function call .



