Flatten an array in Javascript without any inbuilt functions
2 min readJun 3, 2020
As of 2020, we have ES2019 which introduced a great method called flat () to deal with nested arrays and get the flattened array. The flat() method accepts a single parameter <depth>.
The depth defines the layers in the array. By default, it`s 1.
const oneLevel = [ '🔥', ['🦁', '🍕'], '🦋' ];
console.log( oneLevel.flat() ); //depth: 1
// ['🔥', '🦁', '🍕', '🦋'];const twoLevel = ['🔥', [ '🦁', ['👸', '🤴'], ' 🦋' ], '🍉'];console.log( twoLevel.flat() ); // depth: 1
['🔥', '🦁', ['👸', '🤴'], ' 🦋', '🍉']console.log( twoLevel.flat(2) ); // depth: 2
// ['🔥', '🦁', '👸', '🤴', ' 🦋', '🍉']
Infinite Nested Arrays using flat()
const infiniteDeep = [...[], [..[..[[]..]..]..]]
infiniteDeep.flat(Infinity);
But, flat
is a super new feature in the world of Javascript so all browser support is not there. Therefore, we calculate this using raw way
Infinite Nested Arrays without flat()
function flatArray(arr) { let result = []; // In this we`ll save the output; let main = arr, first; while(main.length > 0) { //1. Looping it first = main[0]; if(Array.isArray(first)) { Array.prototype.splice.apply(main, [0, 1].concat(first)); } else { result.push(first); main.splice(0, 1); }} return result;}console.log(flatArray(arr)); // Flatten array [.........]
There you go. A simple yet useful function in the world of javascript. Hope this was helpful.