Skip to content

Edvins Antonovs

How to flatten an array in JavaScript

During the interviews, you can come across code challenges where you need to implement your own version without using the native Array.prototype.flat() method. Roughly there are nearly ten ways how you can write it in JavaScript. It's a commonly asked question which checks your knowledge of JavaScript array methods and the concept of recursion.

Initially, I encountered this code challenge while preparing for front-end interviews on GreatFrontEnd.

The approach I use to solve this challenge is very straightforward. I start by creating an array (temp) which we will return at the end of the function.

Then we loop through the element in the input array. If the element is an array, recursively flatten it and add its elements to the flattened array.

1temp.concat(flatten(ele))

If the element is not an array, add it to the flattened array as is. Then we return the flattened array.

1function flatten(value) {
2 let temp = [];
3
4 for (let i = 0; i < value.length; i++) {
5 let ele = value[i];
6
7 if (Array.isArray(ele)) {
8 temp = temp.concat(flatten(ele));
9 } else {
10 temp.push(ele);
11 }
12 }
13
14 return temp;
15}
© 2024 by Edvins Antonovs. All rights reserved.