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

learndaily1

Think1s

Posted on June 2, 2022

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

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
learndaily1
Think1s

Posted on June 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About