🚀 AI SaaS Starter is now live!

Start building your SaaS in a Day

50% OFF

Use code FIRST50

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 Nov 11, 2025


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 :)

Further Learning

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

🚀

Love this content? Share it!

Help others discover this resource

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Other Related Blogs

Top 10 React Performance Optimization Techniques [React Interview]

Anuj Sharma

Last Updated Nov 10, 2025

Find the top React Performance Optimization Techniques specific to React applications that help to make your react app faster and more responsive for the users along with some bonus techniques.

Polyfill for map, filter, and reduce in JavaScript

Anuj Sharma

Last Updated Oct 2, 2025

Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.

Implement useFetch() Custom Hook in React (Interview)

Anuj Sharma

Last Updated Nov 10, 2025

Find the step-by-step explanation of the useFetch custom hook in React that helps in fetching the data from an API and handling loading, error states.

Master Hoisting in JavaScript with 5 Examples

Alok Kumar Giri

Last Updated Jun 2, 2025

Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.

Implement Infinite Currying Sum: JavaScript Interview Question sum(1)(2)(3)

Anuj Sharma

Last Updated Nov 8, 2025

In this post, we will going to cover the step-by-step implementation of Infinite Currying Sum with a code example. This is one of the most common JavaScript Interview questions.

setTimeout Polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Aug 3, 2025

Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.

Stay Updated

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

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved