How to flatten nested array in Javascript
How to flatten nested array in Javascript
In Javascript, we can flatten a multidimensional array recursively in a different method. Listing the most efficient solutions to flatten the nested array into a single array.
- We can use the array flat() method
- We can use the array reduce() method
- We can use the array map() method
Solution 1:
The best solution is we can use the flat() method to flatten nested array in Javascript. And when a flat method is been used it is necessary to pass the Infinity as the argument.
// an multi dimentional array var array = ['name', 'email', ['phone', ['address']], 'department', ['it']]; // Sol 1 : flat with infinity console.log(array.flat(Infinity)); // output // ["name", "email", "phone", "address", "department", "it"]
Solution 2:
Use the reduce function to flatten the multidimensional array. Reduce method checks whether the current item is value or array. If the current item is value it will be concatenated otherwise flatByReduce method will be called recursively.
// an multi dimentional array var array = ['name', 'email', ['phone', ['address']], 'department', ['it']]; // Sol 2: use reduce const flatByReduce = (param) => { return param.reduce(function(result, nextItem) { return result.concat(Array.isArray(nextItem) ? flatByReduce(nextItem) : nextItem); }, []); } console.log(flatByReduce(array)); // output // ["name", "email", "phone", "address", "department", "it"]
Solution 3:
We can also use the map method to flatten nested array in Javascript into a single array. Map method checks whether the current item is value or array. If the current item is value it will be returned otherwise flatten method will be called recursively
// an multi dimentional array var array = ['name', 'email', ['phone', ['address']], 'department', ['it']]; // Sol 3: use map const flatten = (param) => { return [].concat(...param) } const flatByMap = (param) => { return flatten( param.map(item => Array.isArray(item) ? flatByMap(item) : item ) ); } console.log(flatByMap(array)); // output // ["name", "email", "phone", "address", "department", "it"]