Flatten a multidimensional JS array

engrmahabub
Mahabubur Rahman
Published on Dec, 16 2023 1 min read 0 comments
image

How to flatten a multidimensional 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()

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 =["@", "#", [["$", "%"], "^", "&", ["*", "+", "-", "/"]], "?"]

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


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

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


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

 

 

 

0 Comments