Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
•4 min read•View as Markdown

In this blog we are going to cover about flatten array and nested array why flatten array are useful? and how to convert a multidimensional array into single array.

Topic cover:

  • What nested arrays are

  • Why flattening arrays is useful

  • Concept of flattening arrays

  • Different approaches to flatten arrays

  • Common interview scenarios

What nested array are?

Nested array is simply array inside array ( array of array ). Sometimes we know them 2D and 3D array multidimensional array but is all nested array are 2D or 3D array? so the answer is no it can be N no. of dimensional.

const arr = [1, 2, 3, [4, 5], 6, [7, 8]];

This is the example of simple nested array.

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
console.log(arr[0][1]);

// Output: 2

This is the example of 2D array and get data through indexing.

let arr = [
  [[1, 2], [3, 4]], 
  [[5, 6], [7, 8]] 
];

console.log(arr[0][1][0]);
// Output: 3

This is the example of 3D array and get data from it.

Why flattening arrays is useful?

Above we see about nested array and see if nested array is goes into depth so it is getting be complex. Suppose if data comes through API with these above nested array like so it is getting be difficult to get filter data form them.

There flatten is useful where a nested array convert into flat or simple array. There are multiple way to do flat with predefine method or without predefine methods.

Different approaches to flatten arrays

Multiple way to do flat array let's see first with predefine methods.

const arr = [1, 2, 3, [4, [5, [6]]], [6, 7]];
console.log(arr.flat());

// Output: [ 1, 2, 3, 4, [ 5, [ 6 ] ], 6, 7 ]


const arr = [1, 2, 3, [4, [5, [6]]], [6, 7]];
console.log(arr.flat(2));

// Output: [ 1, 2, 3, 4,  5, [ 6 ], 6, 7 ]

const arr = [1, 2, 3, [4, [5, [6]]], [6, 7]];
console.log(arr.flat(3));

// Output: [ 1, 2, 3, 4,  5,  6 , 6, 7 ]

In array there is a predefine function flat which convert into flat and it behave differently when we pass number basically the number represent how many level of depth array should be flat by default it goes 1 and see when pass 2 so the output is changed same with 3 so now the question is that? what happen when array is n times nested and we don't know?

There we define Infinity it goes n number of nested array and then make flat.

const arr = [1, 2, 3, [4, [5, [[23, [12, 23]],6]]], [6, 7]];
console.log(arr.flat(Infinity));

// Output: [ 1, 2, 3, 4, 5, 23, 12, 23, 6, 6, 7]

Here we can see how the Infinity works.

Now let's see without predefine methods.

function flatArray(arr){

    let newArray = [];
    
    for(const value of arr){
        if(Array.isArray(arr)){
            newArray.push(...flatArray(value));
        }
        else{
            newArray.push(value);
        }
    }
    
    return newArray;
}

const nestedArr = [1, 2, 3, [4, 5, [6]]];
console.log(flatArray(nestedArr));

// Output: [ 1, 2, 3, 4, 5, 6 ];

Explaining the code as interview perspective

In this example flatArray function take array as a parameter and inside function define new empty array newArray and then through for..of loop iterate value and the value is array or no if array so call again same function for that value and when the function resolve the value push the value from newArray before push spread it. it is called recursive approach.

function flattenDeep(arr) {
  return arr.reduce((acc, curr) => {
    return acc.concat(Array.isArray(curr) ? flattenDeep(curr) : curr);
  }, []);
}

const deepNested = [1, [2, [3, 4], 5]];
console.log(flattenDeep(deepNested));

// Output: [ 1, 2, 3, 4, 5 ]

Here we can same thing with reduce and concat it is also a recursive approach.

It is become easy when we knowledge have recursion and array in js.