DEV Community

Sonu kumar
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];
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (2)

Collapse
 
oculus42 profile image
Samuel Rouse

Hello! I think there is some miscommunication in the description of your article. Your description of a flattened array is incorrect to my understanding. "Flattened" describes the array after you remove the nested Arrays/additional "dimensions".

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.

Collapse
 
mesonu profile image
Sonu kumar

That we know that we can fix this issues using inbuilt method, but here I am providing info how can we solve without inbuilt function.
I have described the to reduce the multi dimensional array to single dimensions array is know flatter array.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay