Blog/NotesConcept

Flatten Nested Array in JavaScript using Recursion

Understand step by step how to flatten nested array in javascript using recursion, also explore the flatten of complex array of object.

Intermediate

Anuj Sharma

Last Updated Feb 21, 2026


Flatten Nested Array in JavaScript using Recursion

Nested array are quite commonly used in the javascript for data manipulations, and that's why we often need to Flatten nested array in javascript for processing purpose.

Flattening a nested array involves converting a multi-dimensional array into a single-dimensional array by extracting all elements and combining them into one array.

In this blog post, we will explore how to flatten nested arrays using recursion. We will also cover the ways to handle complex arrays of objects and flattening them effectively.

Let's Understanding Recursion Approach

In the context of flattening nested arrays, recursion can be used to iterate through the elements of an array, checking if each element is an array itself. If an element is an array, the function recursively flattens that array until all nested arrays are flattened.

Flatten Nested Array in JavaScript

Let's start by creating a function that can flatten a nested array using recursion. We will define a function called flattenArray that takes an array as input and returns a flattened array.

function flattenArray(arr) {
    let flatArray = [];

    arr.forEach((element) => {
        if (Array.isArray(element)) {
            // Recursive call
            flatArray.push(...flattenArray(element));
        } else {
            // Recursive call
            flatArray.push(element);
        }
    });

    return flatArray;
}

Example usage

const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

In the flattenArray function, we iterate over each element of the input array and handle 2 cases

  1. If an element is an array, we recursively call flattenArray on that element and spread its contents into the flatArray.
  2. If the element is not an array, we simply push it into the flatArray. This process continues until all nested arrays are flattened.

Flatten Nested Arrays of Objects

Flatten nested arrays of objects adds an additional layer of complexity. In this scenario, we need to consider not only nested arrays but also nested objects within the array.

Let's modify our flattenArray function to handle arrays of objects.

function flattenArray(arr) {
    let flatArray = [];

    arr.forEach((element) => {
        if (Array.isArray(element)) {
            flatArray.push(...flattenArray(element));
        } else if (typeof element === 'object' && !Array.isArray(element)) {
            flatArray.push(...flattenArray(Object.values(element)));
        } else {
            flatArray.push(element);
        }
    });

    return flatArray;
}

Example usage with array of objects

const arrayOfObjects = [{ a: 1 }, { b: [2, 3] }, { c: { d: [4, 5] } }];
const flattenedArray = flattenArray(arrayOfObjects);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]

In this updated version of flattenArray, we check if the element is an object and not an array. If it is an object, we extract its values using Object.values() and recursively flatten the values.

This modification allows us to handle arrays of objects effectively and flatten them into a single-dimensional array.

Final Thoughts

Flattening nested arrays in JavaScript using recursion is an important problem both in development and in frontend interviews. By understanding how recursion works and applying it to flatten nested arrays, you can efficiently process and manipulate array data in your frontend development projects. 

Thank you for reading this blog post on flattening nested arrays in JavaScript using recursion. Stay tuned for more frontend development and interview related stuff.

Happy Coding :)

Asked in Frontend Interviews:

  1. Frontend Interview Experience at Flipkart | UI Engineer 1

Further Learning

  1. Best Resources to prepare for JavaScript Interview
  2. Most asked Machine Coding Round Questions & Resources

Love this Blog? Share it Now!

Help others discover this resource

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀


Learn Next

Featured

20 Most Asked Custom Hooks in React for Interviews

Top 10 React Performance Optimization Techniques25 Top JavaScript Interview Questions for BeginnersHow to create custom useInfiniteScroll Hook in ReactImplement useThrottle Custom Hook In React

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀

Share your expertise

Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.

Build your portfolio

Help the community

Sharpen your skills

Earn goodies

Other Related Blogs

Implement JSON Parse polyfill in JavaScript

Anuj Sharma

Last Updated Jun 15, 2026

Explore the code implementation of JSON Parse Polyfill in JavaScript that can parse a string into valid JSON.

Implement JSON Stringify Polyfill in JavaScript

Anuj Sharma

Last Updated Jun 15, 2026

Explore the detailed explanation of the JSON Stringify Polyfill implementation in JavaScript to prepare for the frontend interviews.

What is javascript:void(0) and How it Works?

Anuj Sharma

Last Updated Jun 15, 2026

A comprehensive explanation about using javascript:void(0) in javascript. When to use javascript:void(0) and how it works with examples of using it with anchor tag.

Understand JavaScript Date Object with Examples (for JavaScript Interviews)

Anuj Sharma

Last Updated Jun 15, 2026

Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.

Apply Polyfill in JavaScript: Step by Step Explanation (For Interview)

Anuj Sharma

Last Updated Jun 15, 2026

Understand how the apply method works in JavaScript and cover step by step-by-step explanation of the apply method polyfill in JavaScript to understand its internal implementation.

Memory Leak in JavaScript: 4 Most Common Reasons

Anuj Sharma

Last Updated Jun 15, 2026

A quick guide to understanding the most common reasons and how to avoid Memory Leak in JavaScript with examples to build more robust web applications.

How to Format Phone Number in JavaScript (JavaScript Interview)

Anuj Sharma

Last Updated Jun 15, 2026

Learn the best & quickest way to format phone number in JavaScript with or without country codes. This will help websites to show the phone numbers in a more human-readable format.

Ultimate guide to REST API calls using Fetch: Machine Coding Essential

Vivek Chavan

Last Updated Jun 15, 2026

You will get a clear understanding about working with any rest api and common concepts asked during interviews

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

All in One Preparation Hub to Ace Frontend Interviews. Master JavaScript, React, System Design, and more with curated resources.

Consider Supporting this Free Platform

Buy Me a Coffee

Product

HomeFrontend InterviewFrontend JobsQuestionsNewInterview ExperienceBlogsToolsLeaderboardFrontendGeek Chrome extensionGet the extension on the Chrome Web Store →

© 2026 FrontendGeek. All rights reserved