Flattening an Array Using Recursive Functions in Javascript

Kyle Riner
The Startup
Published in
2 min readAug 24, 2020
Photo by Kalen Emsley on Unsplash

Javascript can seem daunting, and when dealing with complex problems such as flattening an array, the answer can seem unintuitive at best. However, there is a simple way that the problem of arrays in arrays can be solved, and that’s using Recursive Functions.

To begin, let me explain what an “Unflattened” array looks like. An unflattened array is an array that contains arrays within it. Think of it like peaks and valleys, where the lowest level array contains all other arrays within, and those arrays also contain arrays within them. It will look something like this in code:

let unflatArray = [55, 23, [45, 7, [9, 2, [67], 6, 1], 54, 23, [99, 92], 45]]

As you can see, there are numbers contained on each level, building up to the “Top” with 67, though there is another smaller peak where 99 and 92 are. But how does go through the base array, then all the arrays within, one by one? That’s where Recursive functions come in.

A recursive function is a function that calls on itself. There is the first call to the function, then many calls and repetitions of the same function within itself, depending on how the recursive function gets called again. It’s perfect for unflattened arrays because we can choose when to sequentially go through one array, then pause that midway through once we run into another array and start doing that array, rather than trying to organize the unflattened array, we’re just going to traverse it like any other array, just in much smaller bite-sized chunks. Let’s have a look at how this is constructed:

As you can see, the function itself is actually extremely simple. What we’re doing is creating a function that will take an array. It will then iterate over that array. For each iteration, if the type of the current array item is a number, it will add that number to the new flatArray list. However, if it does not see a number, it will run the flattenArray function from within the flattenArray function. Each time a new iteration of the function is running, it will handle that function first before going back to the for loop in the previous iteration of flattenArray. That way, the end result is a single array with the numbers in the same order that they came in as in the unflattened array. You may also change the “typeof” conditional to equal other data types like strings or booleans, to fit your individual needs.

Nevertheless, this simple usage of Recursive Functions might even land you a job at Facebook, as this is a common technical interview question that they ask of their prospective employees. Keep it in mind!

--

--

Kyle Riner
The Startup

Full Stack Web Developer actively seeking position in Austin, TX.