Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
3 min read
Array Flatten in JavaScript

What are nested arrays

Before we understand nested arrays, we have to understand what arrays are

  • Arrays are nothing, It is just a list of similar or multiple different data types

  • Let's understand with a real-world example - Suppose you have a box, you open it and find another box, and you open the inner box and find another box, and so on. This type of structure is known as nesting

  • Similarly, nested arrays are an array of arrays in a nested way - In simplified terms, an array inside an array, and can also have an array inside an array

Example:

[1, 2, [3, 4], [5, [6, 7]]]

Why flattening arrays is useful

First, we understand that what is meant by flattening, its meaning is to flatten a nested array into a simple array

Let's suppose we have a nested array of numbers. We want to add all numbers, so flattening can simplify the task

Example:

const arr = [1, 2, [3, 4], [5, [6, 7]]] //nested array

const output = arr.flat(Infinity);
console.log(output) // [1,2,3,4,5,6,7\

Now we can easily loop through the array and add all the numbers. If we do not do the flattening, adding all the nested numbers is more complex; we have to use recursion and multiple nested for loops

Concept of flattening arrays

arr = [1, [2, [3, 4]]];

step 1: If any primitive datatype is found, then insert that into the result array result=[1]

step 2: If any non-primitive datatype is found, then recall the recursive function

step 3: If the array has no elements, return the result array

result = [1,2,3,4];

Different approaches to flatten arrays

There are multiple ways to do flatten of any array

Loop method: If any value is found, add that to the result array, and if it is an object, then open it using recursion

Recursion method: We already covered it in the concept of flattening an array

In-built method:

arr.flat(Infinity)

Common interview scenarios

There are some common questions that an interviewer asks you

  • What is an Infinity means in the flat method

  • Flatten an array without using recursion

  • Implement flatten array where the depth is given

  • The interviewer may ask to implement a flattened array. Here, I implement it

function  flatten(arr) {
    const result = [];
    for(let i=0; i<arr.length; i++){
        if(!Array.isArray(arr[i])){
            result.push(arr[i])
        }
        else{
            const temp = flatten(arr[i]);
            result.push(...temp)
        }
    }
    return result;
}

console.log(flatten([1,2,[3,4,[5,6]]]));

steps:

  • Here, I take a result array to store the flattened array

  • Loop through the array. If the array element is an array itself, then I do recursive call for that element

  • If the element is a normal value, not an array, then I insert it into the result array

  • When the last inner array is fully traversed through a loop, then return and push the returned element into the result array

  • At the end, return the result array