JavaScript Interview — how to flatten an array

function flatten(arr) {
...
while(!isFlat)
// flatten some more
}
function flatten(arr) {
let reachedEnd = false;
let idx = 0;

while (!reachedEnd) {
// arrays can be multi-nested [[]], hence the inner while
while(Array.isArray(arr[idx])) { ... flatten ...}
idx++; // reached end after enough iterations
}
return arr;
}
function flatten(arr) {
let reachedEnd = false;
let idx = 0;

while (!reachedEnd) {
while(Array.isArray(arr[idx])) {
arr.splice(idx, 1, ...arr[idx]);
}
if (idx === arr.length) {
reachedEnd= true;
}
idx++;
}
return arr;
}
function flattenToDepth(arr, depth = 1) {
let reachedEnd = false;
let idx = 0;

while (!reachedEnd) {
let atDepth = 1;
while(Array.isArray(arr[idx]) && atDepth < depth) {
arr.splice(idx, 1, ...arr[idx]);
atDepth++;
}
if (idx === arr.length) {
reachedEnd= true;
}
idx++;
}
return arr;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store