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]

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]

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]

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

Voila๐
Let me know your thoughts about it ๐ and if you like it share it with others.

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"
]
}
]
}
]

Thanks a lot!

In second example it says flatten(test) not arr. Great tut anyway ๐

Mukul Singhal

Thanks ๐ . Edited

Kushagra Mehta

Waiting for the series now๐

rancy98

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

Mukul Singhal

๐