Coding Challenge - #19: Flatten Nested Array

Write a function flatten(arr, depth) that flattens a nested array up to the specified depth (defaulting to 1). For example, flatten([1, [2, [3, [4]]]], 2) should return [1, 2, 3, [4]].

function flatten(arr, depth = 1) {
  // Your code here
}

Rules:

  • Do not use the built-in Array.prototype.flat() method.
  • Must support a custom depth parameter that defaults to 1.
  • Return a new array without mutating the original input.

Post your solution as a reply. Answer goes up in about a day.

function flatten(arr, depth = 1) {

if (depth <= 0) return […arr];

const result = [];

for (const item of arr) {

if (Array.isArray(item)) {

  result.push(...flatten(item, depth - 1));

} else {

  result.push(item);

}

}

return result;

}

// Example:

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

// [1, 2, 3, [4]]

This recursively flattens the array up to the specified depth and creates a new array without modifying the original.

Challenge solution: The challenge asks for a JavaScript function to flatten a nested array up to a specified depth without using the built-in flat method.

One way to do it:

function flatten(arr, depth = 1) {
  const result = [];

  function recurse(currentArr, currentDepth) {
    for (let i = 0; i < currentArr.length; i++) {
      const item = currentArr[i];
      if (Array.isArray(item) && currentDepth > 0) {
        recurse(item, currentDepth - 1);
      } else {
        result.push(item);
      }
    }
  }

  recurse(arr, depth);
  return result;
}

Why:
This solution uses a recursive helper function to traverse the input array. It checks if an item is an array and if the current flattening depth allows further recursion. If both conditions are met, it calls itself with the nested array and decremented depth; otherwise, it pushes the item directly to the result array. This approach correctly handles the depth parameter and avoids mutating the original array.


Got it: @emmawalter5 :trophy:

First-answer leaderboard

  1. @Apexcodes - 6 (firsts) :trophy:
  2. @emmawalter5 - 6 (firsts) :trophy:
  3. @kirupa - 6 (firsts) :trophy:
  4. @adnanahmed - 2 (firsts)

The recurse helper function makes the result array accessible without passing it through every function call. That’s a clean way to manage state in a recursive structure.