# Array Flattening

`Question  :  Given a nested array on any depth and we need to make it a single array.Eg. :-  Array = [1,2,[3,4,[5,6],7],8] || [1,2,[3,4],5] || [1,2,[3,[4,[5]]]]Output :- [1,2,3,4,5,6,7,8] | [1,2,3,4,5] || [1,2,3,4,5] || [1,2,3,4,5] respectively for every input array`

# Array.prototype.flat() :-

`Flatten 1 level deep const arr1 = [1, 2, [3, 4]]arr1.flat(); ouptut -  [1, 2, 3, 4]const arr2 = [1, 2, [3, 4, [5, 6]]];arr2.flat();output - [1, 2, 3, 4, [5, 6]]// Flatten 2 levels deepconst arr3 = [2, 2, 5, [5, [5, [6]], 7]];arr3.flat(2);output - [2, 2, 5, 5, 5, [6], 7];** For flattening every level depth we need to pass 'Inifinity' as aurguments to the flat() method **// Flatten all levelsconst arr4 = [2, 2, 5, [5, [5, [6]], 7]];arr4.flat(Infinity);output - [2, 2, 5, 5, 5, 6, 7]; For reference please click here`
`const flatten = function(arr, result = []) {  for (let i = 0, length = arr.length; i < length; i++) {    const value = arr[i];    if(Array.isArray(value)) {      flatten(value, result);    } else {      result.push(value);    }  }  return result;}Reference taken from here`
`function deepFlatten(arr) {  return flatten(           // return shalowly flattened array    arr.map(x=>             // with each x in array      Array.isArray(x)      // is x an array?        ? deepFlatten(x)    // if yes, return deeply flattened x        : x                 // if no, return just x    )  )}Reference taken from here`

--

--

--

## More from Rakesh Kumar Shaw

JavaScript Enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

## Rakesh Kumar Shaw

JavaScript Enthusiast