DEV Community

Think1s
Think1s

Posted on

JS Interview Question #3 (Polyfill for array.flat())

Read more articles in Think1s

const arr = [2, 3, 4, [5, [6, 7, [8, 9]]]];
  function flatArray(arr, depth = 1) {
    return depth > 1
      ? arr.reduce((acc, curr) => {
          acc = acc.concat(
            Array.isArray(curr) ? flatArray(curr, depth - 1) :curr);
          return acc;
        }, [])
      : arr;
  }
  console.log(flatArray(arr, Infinity));
Enter fullscreen mode Exit fullscreen mode

Click here Object flattening

Read more articles in Think1s

Top comments (0)