Sonu kumar

Posted on

# What is a flattened array and How do solving flatten array problem using recursion functions in JavaScript?

## Introduction:

First Lets understand What is a flattened array. A flattened Array is an Array, but this array is a form of a multi-dimension array, a nested array or an array containing another array.

Flatten is one approach or technique that helps to reduce the multidimensional array to one one-dimensional array known as flatten.

Sometimes we require this kind of data when we are working on projects or solving a problem then it helps to pass the group of the data set using a flattened array.

Example:

``````// This is a flattened array
let arr = [1,44, [2, [3,9], 67], 9];
``````

## How to solve a flattened array problems?

There are multiple ways to solve this kind of problem but here, I am going to explain using the Recursion method, this is one of the best approaches to solve this kind of problem.

Here, I am not going to details explanation of the Recursion, But I will give a little overview of about, if you want to know more about I will create a separate post for that.

Recursion is a programming approach to solve the issues of repetition kinds of works, which calls itself directly or indirectly until not match the given particular conditions, if matched then the function stops the calling itself.

`````` // This is a flattened array
// Input:
let arr = [1,44, [2, [3,9], 67], 9];

// Function Defin
function recur(a) {
let newArr = [];
for (let i =0 ; i < a.length; i++) {
const element = a[i];
if (Array.isArray(element)) {
// Function calling itself recursion
newArr.push(...recur(element))
} else  {
newArr.push(element)
}
}

return newArr;
}

console.log(recur(arr))
Output:
[1,44,2,3,9, 67, 9]

// We can also write the same code using for each:
function flattenArray(items) {
const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});

return flat;
}

onsole.log(flattenArray(arr))
output:
[1,44,2,3,9, 67, 9]
``````

And while it is an interesting problem which you can resolve this recursively, there is also the built-in `Array.prototype.flat()` to do this work.