DEV Community

Shamun Khatri
Shamun Khatri

Posted on

Implement Array.prototype.flat() Solution

Implementing Array.prototype.flat() Using an Iterative Approach

Introduction
The JavaScript method Array.prototype.flat() is used to flatten nested arrays up to a specified depth. If no depth is provided, it defaults to flattening one level deep. In this guide, we’ll implement the flat() method using an iterative approach with a stack, providing an efficient and readable solution.

We can solve this problem by both iterative and recursive methods but here I am only implementing the iterative way of solving it.

Most of the solutions on the internet are not the proper solution that handles sparse arrays and undefined values. There may be better solutions available but this works for me and the comment section is open if you know the better way.

Problem
source - https://bigfrontend.dev/problem/implement-Array-prototype.flat

Problem Description
Given a nested array, we need to flatten it up to a specified depth.

const arr = [1, [2], [3, [4]]];

flat(arr);
// [1, 2, 3, [4]]

flat(arr, 1);
// [1, 2, 3, [4]]

flat(arr, 2);
// [1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

Iterative Solution with Stack

/**
 * @param { Array } arr
 * @param { number } depth
 * @returns { Array }
 */
function flat(arr, depth = 1) {
  const flatArray = [];
  const stack = [];
  for (const index in arr) {
    stack.push([arr[index], depth]);
  }

  while (stack.length > 0) {
    let lastElement = stack[stack.length - 1];
    if (!lastElement) {
      stack.pop();
      flatArray.push(lastElement);
      continue;
    }
    const [item, depth] = stack.pop();
    if (Array.isArray(item) && depth > 0) {
      for (const index in item) {
        stack.push([item[index], depth - 1]);
      }
    } else {
      flatArray.push(item);
    }
  }

  return flatArray.reverse();
}

Enter fullscreen mode Exit fullscreen mode

This implementation efficiently flattens arrays providing a clean, scalable solution. Let me know if you'd like further enhancements! 🚀

Top comments (0)