Implement a function to flatten a nested array. Example: `[1, [2, [3, 4]], 5] -> [1, 2, 3, 4, 5]`

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Approach 1: Using built-in Array.prototype.flat() (Modern & Simplest)

This is the most straightforward way in modern JavaScript.

function flattenArray(arr) {
  // Use Infinity to handle arbitrarily deep nesting.
  return arr.flat(Infinity);
}

const nested = [1, [2, [3, 4]], 5];
console.log(flattenArray(nested)); // [1, 2, 3, 4, 5]

Approach 2: Recursive

This approach manually checks for nested arrays and flattens them.

function flattenArrayRecursive(arr) {
  let result = [];
  arr.forEach(item => {
    if (Array.isArray(item)) {
      result = result.concat(flattenArrayRecursive(item));
    } else {
      result.push(item);
    }
  });
  return result;
}

const nested = [1, [2, [3, 4]], 5];
console.log(flattenArrayRecursive(nested)); // [1, 2, 3, 4, 5]