Let’s flatten that multi-dimensional array
Let’s flatten that multi-dimensional array

Solving one of the recurring interview questions for JavaScript developers

Hi everyone, how are you doing? This is my first article for the year 2020 and let’s get into some problem-solving exercise today.

This is one of the recurring interview questions for JavaScript developers. We will go through both the problem and the solution in this post.

Problem statement:

Write a function to flatten a multi-dimensional array (depth can go till n-levels) and the result should not contain any null/undefined values.

Sample input:

var testArray = [1, 2, null, [4, undefined, [11, 10]], 6, [7, null, 0], null, 9];

Expected output:

[1, 2, 4, 11, 10, 6, 7, 0, 9]

Solution 1: using ‘for’ loop and ‘recursion’

// the utility function to flatten input array function flattenArray(arr) {

let result = []; for(let index = 0; index < arr.length; index++) {

const currentValue = arr[index];

if(Array.isArray(currentValue)) {

result = [...result, ...(flattenArray(currentValue))]; // we can also use concat method to achieve the same result

// result = result.concat(flattenArray(currentValue)); } else {

if(currentValue != null) {

result.push(currentValue);

}

}

}

return result;

}

// use the code below to execute and test the functionality const testArray = [1, 2, null, [4, undefined, [11, 10]], 6, [7, null, 0], null, 9]; const result = flattenArray(testArray); console.log(result); // [1, 2, 4, 11, 10, 6, 7, 0, 9]

Let’s breakdown the implementation to understand the approach:

We create the utility function flattenArray which will take the multidimensional array as input, and return the flattened array with no null/undefined items as output. Create an array called result to which will contain the final array to be returned. Loop over the input array to iterate over each item. I have used for loop here for simplicity. We can also use forEach loop or reduce ( a higher-order function present on Array prototype) to achieve the same result. For each item of the current array, we need to check first if that element is an Array? In the above example, Array.isArray function is used to check the same. If the current element is not an Array, we can go ahead and push that element onto the result array after null check. Remember, we need to eliminate any null/undefined values from the Array. If you notice, in the code, I have used loose equality check for null values (currentValue != null). This was done intentionally so that both null and undefined values get eliminated from the result. But what if the current element is an array? We will have to perform step 3 till 5 again to push the individual items of this new array to existing results array. This can be achieved by using a concept called recursion (where a function calls itself until a condition is met). As the recursive function will also return an array of items, we will now concat the result of recursive function with the already existing results array. This will ensure that the two different arrays get merged. This logic will continue till n-level (here, n is the depth of the input array). I have used the ES6 spread operator to achieve the same result. Finally, when items at all levels of the input array are concatenated into a single-dimensional array, that result is returned from the function. This will be our most-awaited, most precious result that we were coding for.

Now, if you felt that the code is too much, well JavaScript has a simpler solution for you. Presenting a second solution below.
['Anuradha Kumari']
['Programming', 'JavaScript', 'Problem Solving', 'Interview Questions', 'Web Development']