DEV Community

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

Posted on • Edited on

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 ⚡️

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