logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • 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.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Flatten a Nested Array Without Using the Flat Function

author
Generated by
Himadhar Narayan

14/09/2024

JavaScript

Sign in to read full article

Flattening a nested array refers to converting an array that contains other arrays into a single-level array. For instance, if you have an array like [1, [2, [3, 4], 5], 6], the goal is to transform it into [1, 2, 3, 4, 5, 6].

While the flat() function available in modern JavaScript can accomplish this efficiently, it's beneficial to understand how we can do it using plain loops and recursion.

Example of a Nested Array

Let’s use a nested array for our example:

const nestedArray = [1, [2, [3, 4], 5], 6];

Here's how we can flatten this array without using the flat() function.

Method 1: Using Recursion

One approach to flatten a nested array is through recursion. The idea is to iterate through each element of the array. If an element is an array, we call the function again on that array. If it's not, we add it directly to the result.

Here’s how we can implement this:

function flattenArray(arr) { let result = []; arr.forEach(item => { if (Array.isArray(item)) { result = result.concat(flattenArray(item)); // Recurse if the item is an array } else { result.push(item); // Add the item if it's not an array } }); return result; } const flattened = flattenArray(nestedArray); console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]

Explanation of the Code:

  1. We define a function flattenArray that takes an array as an argument.
  2. We initiate an empty array result, which will eventually hold our flattened result.
  3. Using forEach, we loop over each item in the input array.
  4. Inside the loop, we check if the current item is an array using Array.isArray().
  5. If it is an array, we call flattenArray recursively on that item. The result of this call is concatenated to our existing result.
  6. If the item is not an array, we simply push it to the result.
  7. Finally, we return the fully flattened array.

Method 2: Using Iteration with a Stack

Another approach to flatten a nested array is to use an iterative method with a stack. This method avoids recursion, which can be beneficial when working with very deeply nested arrays. Here’s how to implement it:

function flattenArrayIterative(arr) { const result = []; const stack = [...arr]; // Spread the original array into a stack while (stack.length) { const item = stack.pop(); // Take the last item from the stack if (Array.isArray(item)) { stack.push(...item); // Push the elements of the array onto the stack } else { result.push(item); // If not an array, add it to the result } } return result.reverse(); // Reverse the result to maintain order } const flattenedIterative = flattenArrayIterative(nestedArray); console.log(flattenedIterative); // Output: [1, 2, 3, 4, 5, 6]

Explanation of the Code:

  1. We define the flattenArrayIterative function.
  2. We initialize an empty array result to store the flattened result and a stack variable initialized with a copy of the input array (...arr).
  3. We use a while loop that runs as long as there are elements in the stack.
  4. Inside the loop, we pop the last element from the stack.
  5. If the popped item is an array, we spread its elements and push them back onto the stack.
  6. If it’s not an array, we push it directly to the result.
  7. Once the stack is empty, we return the result reversed to maintain the original order of elements.

By leveraging these techniques, you gain a deeper understanding of how to handle and manipulate arrays in JavaScript without relying solely on built-in functions.

Popular Tags

JavaScriptNested ArraysArray Manipulation

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

Related Articles

  • Create a Custom Event Emitter in JavaScript

    14/09/2024 | VanillaJS

  • JavaScript Callbacks Unveiled

    22/10/2024 | VanillaJS

  • JavaScript Module Patterns

    22/10/2024 | VanillaJS

  • Deep Cloning Object in JavaScript

    25/07/2024 | VanillaJS

  • Understanding the JavaScript Event Loop

    22/10/2024 | VanillaJS

  • Optimizing JavaScript Performance with a Memoization Function

    14/09/2024 | VanillaJS

  • Implementing a Debounce Function

    14/09/2024 | VanillaJS

Popular Category

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