Flat an Multi Dimensional Array in Javascript

Hello devs, today I'll talk about how to flatten a multi-dimensional array. So what is the term that stands for flattening an array? Flatten means breaking the multi-dimensional array into one-dimensional array. It's quite necessary when we want to loop or simply check if an item exists in an array. So, let's see the example below.

The Example

We'll use the JavaScript in built function called flat() which will flat the array from any number of dimensional array. We can see the some below source code for our example purpose.

let array = [
  1,
  [2,[3,4,5]],
  [6,[7,[8,9]]]
];

console.log(array.flat());

This above example will flatten up to the only a one-dimensional array because flat() method default argument is 1. Look at the below example for more clear concept.

 

let array = [
  1,
  [2,[3,4,5]],
  [6,[7,[8,9]]]
];

console.log(array.flat(Infinity));

But this above example will convert the whole array into one-dimensional array because we provide the Infinity as an flat() aragument. Look at the below example for more clear concept.

 

That's it for today's tutorial. I hope this will be helpful for you. Thanks for reading. ๐Ÿ™‚