logologo
  • Dashboard
  • Features
  • AI Tools
  • FAQs
  • Jobs
  • Modus
logologo

We source, screen & deliver pre-vetted developers—so you only interview high-signal candidates matched to your criteria.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • Pre-Vetted Top Developers

Procodebase © 2025. All rights reserved.

Q: Write a function to flatten a nested array?

author
Generated by
ProCodebase AI

29/10/2024

JavaScript

Flattening an array means converting a multi-dimensional array into a one-dimensional array. For instance, if we have an array like [1, [2, [3, 4], 5], 6], the goal is to transform it into [1, 2, 3, 4, 5, 6].

Step-by-Step Implementation

Here’s how we can achieve this using a simple function in JavaScript.

1. Understanding Input and Output

Before we dive into the code, let’s clarify what our function will do:

  • Input: A nested array of any depth.
  • Output: A flattened array with all the elements.

2. Using Recursion

Recursion is a powerful tool for solving problems that can be broken down into smaller sub-problems. In our case, we can traverse each element of the array, check if it’s an array itself, and if so, call our function again until we get to a non-array element.

3. Writing the Function

Here’s a simple implementation:

function flattenArray(arr) { // Initialize an empty array to hold the result let result = []; // Loop through each element of the input array for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { // If the current element is an array, recurse into it result = result.concat(flattenArray(arr[i])); } else { // If the current element is not an array, add it to the result result.push(arr[i]); } } return result; } // Example usage: const nestedArray = [1, [2, [3, 4], 5], 6]; console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4, 5, 6]

Explanation of the Code

  • Function Declaration: We start with function flattenArray(arr), where arr is our input nested array.
  • Result Array: We initialize an empty array result to store our flattened elements.
  • For Loop: This loop iterates over every element in arr.
    • Check for Array: Using Array.isArray(arr[i]), we determine if the current element is an array.
      • Recursive Call: If it is an array, we call flattenArray(arr[i]) to flatten that sub-array, and concatenate it to result using result.concat().
      • Push Non-Array Element: If the element is not an array, we simply add it to result using result.push(arr[i]).
  • Return Result: Once all elements have been processed, we return the result array.

Edge Cases

  • Empty Arrays: If the input is an empty array, flattenArray([]) will return an empty array [] as expected.
  • No Nested Arrays: If the function receives a flat array (like [1, 2, 3]), it will return the same array, as there are no nested elements.

This method is straightforward and leverages the simplicity of recursion to handle arrays of varying depths. In scenarios where performance is critical or very deep nesting is expected, consider iterative methods or using a stack to avoid potential stack overflow issues with recursion.

With this approach, you can take any complex nested structure and get the clean, flat array you need!

Popular Tags

JavaScriptNested ArraysArray Flattening

Share now!

Related Questions

  • What are closures and how do they work

    29/10/2024 | VanillaJS

  • apply

    17/11/2024 | VanillaJS

  • What is the apply method in JavaScript and when would you use it

    17/11/2024 | VanillaJS

  • What is the difference between let

    17/11/2024 | VanillaJS

  • What is event delegation in JavaScript

    17/11/2024 | VanillaJS

  • What is a higher-order function in JavaScript

    17/11/2024 | VanillaJS

  • Explain prototypal inheritance in JS

    29/10/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design