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

A Layered Approach to Mobile App Protection

A Layered Approach to Mobile App Protection

Attackers use static analysis to understand how your app functions and the data it contains. By using multiple layers of protections like code obfuscation and string encryption, you can prevent attackers from accessing your app.

Read 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.

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Dive into this insightful article, celebrated by the caring DEV Community. Programmers from all walks of life are invited to share and expand our collective wisdom.

A simple thank-you can make someone’s day—drop your kudos in the comments!

On DEV, spreading knowledge paves the way and strengthens our community ties. If this piece helped you, a brief note of appreciation to the author truly counts.

Let’s Go!