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]]]]

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]

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)
  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))
}
  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
}

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))

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

Stay tuned for upcoming articles ⚡️