DEV Community

Cover image for Array Flatten in JavaScript
Anoop Rajoriya
Anoop Rajoriya

Posted on

Array Flatten in JavaScript

Array flatten is the foundation concept of programming, in javascript you will seeing it's use in lots of places like in data fetching form api points, showing data tree as list on pages. In this article we seeing what and why it is, differenct approaches and scenerios you facing in interview on that.


What nested arrays are

In javascript, nested arrays are a simple array whose contain elments or another arrays those can conaint either elments or more arrays. This structure of arrays called nested arrays and also known as multidimentional arrays.

You can think it like a big container box in that we place multiple elements or other boxes as elments those further contain elements in sequence.

[1, [2,3], 4, [5, [6]], 7]
Enter fullscreen mode Exit fullscreen mode

Here example nested array contain 1, then array [2,3], another elment 4, one more array [5, [6]], and lastly element 7. In that there are two nested array first contain 2, 3 and other contain 5 and single value arrya with 6.

Why flattening arrays is useful

Flattening arrays simplify the complex heirarchical structure (a structure contain more structured elments) into a simple linear array structure (a simple version contain only single element). There are several reasons describe why flattening arrays useful:

  • Simplifies Data Processing : many data processing and visualizing library like Chart.js, and Plotly.js requried linear datasets to perform operation in a optimistic way.

  • Data Integration : data fetching from api, reading form other files or databases often give nested structured data to use those data flatteing process are required.

  • Common Use Cases : rendering cards information into dom, using flattening to create well suited formate of cards information are used.

Concept of flattening arrays

Flattening arrays simply means is transforming nested array into an array containing only non-arrya elements. All elments are puting into arrya with concating all nested arryas elements.

Think it like get out all small boxes from container which have elments, taking all those elements and putting it down in sequence into container box.

// Nested array
[1,2,[3,4],[[5],6], 7]

// Flatten array
[1,2,3,4,5,6,7]
Enter fullscreen mode Exit fullscreen mode

Different approaches to flatten arrays

There are multiple ways exist for flatteing arrays in programming but in JavaScript we have native methods supports lets seeing these with other approaches:

Native Array.prototype.flat()

JavaScript support native array flatten method flat() which flatten arrya. By default it only flatten single level nesting. You can pass argument flat(number) represent nesting level which you want to flatten.

Like nested.flat(2) it flatten 2 level nesting, for flattening array completely you can use infinity.

const deeplyNested = [1, [2, [3, 4], 5], 6];

const shalowFlat = deeplyNested.flat() // 1 level flat
console.log(shalowFlat) // output: [1,2,[3,4],5,6]

const deepFlat = deeplyNested.flat(Infinity) // completely flat
console.log(deepFlat) // output: [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

Recursive approach

A recursive approach implemented using custom logic function. In that function call itself to break down nested arrays into single array. To do this there are two important cases need to handle:

  • Base Case: a condition which return elment if it's not an array
  • Recursive Case: a condition which call itself with current elment if its a array and evaluated into flatten arrya.
function flattenRecursively (arr){
    let res = []
    for(let i = 0; i<arr.length; i++){
        if(Array.isArray(arr[i])){
            // recursively call for element which is arrya and merge it into result
            res = res.concat(flattenRecursively(arr[i]))
        }else{
            // merge current not-array elment into result end
            res.push(arr[i])
        }
    }

    return res
}

const highlyNested = [1, [2, 3], [4, [5, 6]]];
console.log(flattenRecursively(highlyNested)); // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Iterative approach

Instead of relies on recursion implicit stack, iterative approach use explicit stack or queue data structure to keep track of array flattening iteration.

In that two array used one for original array copy and other for result. In each iteration, for element shift it form copy and push into result but in case of array shift it form copy and un-wrape all elements and unshift back into copy so in next iteration it will moved into result.

function flattenIteratively(arr){
    let result = []
    let copy = [...arr] // copy original so we don't modify orignal

    while(copy.length){
        const firstItem = copy[0]
        if(Array.isArray(firstItem)){
            // if is array shift it, spread it and unshift it
            copy.shift()
            copy.unshift(...firstItem)
        }else{
            // if element shift it from copy and push into result
            copy.shift()
            result.push(firstItem)
        }
    }
    return result
}

const heavilyNested = [1, [2, [3, 4]], 5];
console.log(flattenIteratively(heavilyNested)); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Common interview scenarios

Prepare about the following points because demonstrating only knowledge of how implementation and working is not enough, you should know why these are and what are the trade-offs for each one.

Implementation without native approaches

Most of the cases interviewer forbid the use of array.prototype.flat(), ask for the implement this becuase thay want to test you thinking ability how you tackle problem and what approach should you prefer.

Here in this scenerio you should need to give the both flatten logic implementation along with its comparison and trade-offs.

  • Recursive approach with its stack overflow scenerios.
  • Iterative approach and efficiency of shift-unshift.

Performance optimizetion trade-offs

Clearly explain each approach optimizetion trade-offs:

  • Native array.prototype.flat(): explain why its optimized for other approaches.
  • Recursive approach: clearly dicuss its call overhead probelm in heavely deep and large arrays.
  • Iterative approach: describe how its use of explicit stack solve recursive stack overflow problem but its unshift-shift reduce efficiency.

Clearly explian shalow vs deep flat

Explain difference of shalow and deep flat, which approach support deep and shalow flat.

  • Native flat(): demonstrate its defalut behaviour and passing level arguments with infinity for completely flatten array.

  • Recursive approach: proper implementation support deep flatten but not efficient for larger array input.

  • Iterative approach: also support deep flatten but have efficiancy problem via use of shift-unshift.


Practising all approaches only not enough for taking control of interview, proper mastering need to build a mental understading. Understading how logic work and tracing on paper for different examples help to build solid understading.

Top comments (0)