![image](/static/img/ProfessionslsCommunity.png)
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.