DEV Community

Cover image for Deep Flatten an Array
Mukul Singhal
Mukul Singhal

Posted on

Deep Flatten an Array

Hello all👋,

In this series we will see a lot of question that are asked in javascript interviews so get ready for it

In this article we will see How to flatten an deeply nested array for example

[1,[2,3,[4,5]]] and convert in into [1,2,3,4,5]

We will learn to flatten an array in 2 ways

  1. Using built in function (flat())

  2. Using recursion

1. Using Flat() method in Javascript

The flat() method is an inbuilt array method that flattens a given array into a newly created one-dimensional array. It concatenates all the elements of the given multidimensional array, and flats upto the specified depth.

var newArr = arr.flat(depth)

By default, the depth limit is 1. It can be 1 to Infinity.



const arr = [1,[2,3,[4,5]]];

  // Setting the depth value to
  // Infinity to deep flatten the array
  const flattened = arr.flat(Infinity);

  console.log(flattened)

  // Output [1,2,3,4,5]



Enter fullscreen mode Exit fullscreen mode

2. Recursively flat an array (Pollyfill)

Now we will see how do it without using any builtin function or basically writing the pollyfill for flat function



//Flatten an array using recursion

const arr = [1,[2,3,[4,5]]]

const flatten = (input)=>{
    let result = []

    if(!Array.isArray(input)) {
        return input;
    }

    for(let data of input) {
        result = result.concat(flatten(data))
    }

    return result
}


console.log(flatten(arr))

// Output [1,2,3,4,5]



Enter fullscreen mode Exit fullscreen mode

Let me explain the code

  1. Iterate through each and every value of an array and check whether it is value or an array using Array.isArray() method.
  2. If it is a value return it and concat it.
  3. If it is an array then follow again from step 1.

Using ES6 features (using reduce())



function flatten(arr) {

    return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);

};

const arr = [1,[2,3,[4,5]]];

const flattened = flatten(arr);

console.log(flattened);

// Output [1,2,3,4,5]




Enter fullscreen mode Exit fullscreen mode

For better understanding of the code Please refer to the gif below.
You can also check this Github repo for the code
Recursion

Voila😃
Let me know your thoughts about it 😃 and if you like it share it with others.

Image description

Top comments (8)

Collapse
 
spotnick profile image
spotnick

Ok, that is cool but what if I have a way more complex structure with objects and nested arrays with objects?

Would it be possible to flatten this into, lets say in somekind of table structure to make searching easier und reverse it after searching?

[
    {
        author: "prachett",
        books: [
            {
                title: "the color of magic",
                characters: [
                    "Rincewind",
                    "Offler"
                ]
            },
            {
                title: "macbest",
                characters: [
                    "Nanny Ogg",
                    "Greebo"
                ]
            }
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

Thanks a lot!

Collapse
 
ahmetustun profile image
Ahmet Ustun

I tried flat with your example and passed Infinity. What I received is the same array. I believe it doesn't support arrays with complex elements.

Collapse
 
kushagra_mehta profile image
Kushagra Mehta

Waiting for the series now😁

Collapse
 
mukul_singhal profile image
Mukul Singhal

😃

Collapse
 
rancy98 profile image
rancy98

What's the expression of the comment? I didn't see it

Collapse
 
adrndev profile image
Adrian Jaskot

In second example it says flatten(test) not arr. Great tut anyway 😊

Collapse
 
mukul_singhal profile image
Mukul Singhal

Thanks 😃 . Edited

Collapse
 
ahmetustun profile image
Ahmet Ustun • Edited

Do you think it's better to use this for creating deep copies of one-dimensional arrays than the spread operator?