logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • AI Interviewer
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

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

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. 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

  • Explain event loop in JavaScript

    29/10/2024 | VanillaJS

  • How does JavaScript handle hoisting and what gets hoisted

    17/11/2024 | VanillaJS

  • What is the difference between let

    17/11/2024 | VanillaJS

  • Write a function to flatten a nested array

    29/10/2024 | VanillaJS

  • const

    17/11/2024 | VanillaJS

  • and var in JavaScript

    17/11/2024 | VanillaJS

  • What are closures in JavaScript and how do they work

    17/11/2024 | VanillaJS

Popular Category

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