DEV Community

Cover image for Flatten an array using javascript
Nand Kishor
Nand Kishor

Posted on • Edited on

4 1

Flatten an array using javascript

Hello Everyone 👋
Thanks for showing the love on the previous post. Today, let's talk about how you can flatten an array using javascript.

Taking a test array:

const arr = [1,2,3,[4,5,[6,7],[8,9,10,[11, NaN, undefined]]]]
Enter fullscreen mode Exit fullscreen mode

now we have to flatten all the elements of this array into a single array so that our output will look like this:

result = [1,2,3,4,5,6,7,8,9,10,11, NaN, undefined]
Enter fullscreen mode Exit fullscreen mode

Starting with a function name i.e, flattenArray that's going to take test array as a parameter.

//function statement

const flattenArray = (input) => {

//initializing the result array

let result = []

//returning the output

return result;
}

//calling the function with test array as argument

flattenarray(arr)
Enter fullscreen mode Exit fullscreen mode
  1. First step we are going to iterate over each element of the array and concatenate each element in the result array. For that we have to run a for loop:

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. (learn more)

//this loop will iterate over each element in the array

for(let data of input){
   result = result.concat(flattenArray(data))
}
Enter fullscreen mode Exit fullscreen mode
  1. We're passing each element to the concat function as this is a recursive function. So when our function input becomes a single element then this function will return an error i.e, input is not iterable hence we have to apply another check condition.
//if the input is not an array this will just return the value

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

Enter fullscreen mode Exit fullscreen mode

Now our code is ready to be execute. Here we're dividing our problem into smaller problem and using recursive function to achieve our final output.

Final Code

const arr = [1,2,3,[4,5,[6,7],[8,9,10,[11, NaN, undefined]]]]

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

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

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

  return result;
}

console.log(flattenArray(arr));
Enter fullscreen mode Exit fullscreen mode

Don't just read this article instead have some hands on Live Demo

Stay tuned for upcoming articles ⚡️

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Or:

[1,2,3,[4,5,[6,7],[8,9,10,[11, NaN, undefined]]]].flat(Infinity)
Enter fullscreen mode Exit fullscreen mode

Which will likely be much faster as it is a native implementation. However, it is a good practice exercise to write it yourself

Collapse
 
shivanshsharma profile image
Shivanshsharma

One of the best blogs on this topic

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️