JSFiddle - React, Tailwind, and code Playground

by Stepan Parunashvili

JavaScript

function flatten(aList) {
  const stack = [[aList, 0]]; 
  const res = [];
  while (stack.length) {
    console.log(JSON.stringify(stack), res)
    const [arr, idx] = stack.pop();
    for (let i = idx; i < arr.length; i++) {
      const el = arr[i];
      if (Array.isArray(el)) {
        stack.push([arr, i + 1]); 
        stack.push([el, 0]); 
        break;
      } else {
        res.push(el);
      }
    }
  }
  return res;
}

console.log(flatten([1, [2, [3], 4], 5]));