JS - 3 : How to flatten a multidimensional array?

Mahabubur Rahman
0

How to flatten a multi-dimensional array?

So our todays problem is we have a multidimensional array we want to convert it to flat array. Say example we have ["@", "#", ["$", "%"], "^", "&", ["*", "+", "-", "/"], "?"] and we want  ["@", "#", "$", "%", "^", "&", "*", "+", "-", "/", "?"].

We can do it very simply as bellow - 

let symbols =["@", "#", ["$", "%"], "^", "&", ["*", "+", "-", "/"], "?"]

Now use flat()

 console.log(symbols.flat()) // ["@", "#", "$", "%", "^", "&", "*", "+", "-", "/", "?"]

So We can use array.flat() method for flatten one level multi-dimensional array. But if more then one level multi-dimensional array?

let symbols2 =["@", "#", [["$", "%"], "^", "&", ["*", "+", "-", "/"]], "?"]
console.log(symbols2.flat()) // ["@", "#", ["$", "%"], "^", "&", ["*", "+", "-", "/"], "?"]

But we want full flat array. Now use Infinity keyword inside flat() method as bellow - 

console.log(symbols2.flat(Infinity)) // ["@", "#", "$", "%", "^", "&", "*", "+", "-", "/", "?"]

So we can pass Infinity parameter to  array.flat method to full flatten any level multi-dimensional array.


Post a Comment

0Comments
Post a Comment (0)