How to Flatten a Nested Array in JavaScript?

If an array contains one or more arrays as its elements, it is called a nested array. And in programming, the nested arrays are very common in use.

Example of a nested array:

// A nested array in JavaScript
const numbers = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

The process of converting a nested array into a flattened(one-dimensional) array is called flattening.

For example, if we convert the above nested array into a flattened array, it will look something like this:

// Flattened Array

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

There are different methods that we can use to flatten an array. Let’s discuss a few of them.


1. Using the Array.flat() Method

The Array.flat() method creates a new array that contains all elements of the original array but in the flattened format.

See the following example:

// Flatten Nested Array

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

const flatNumbers = numbers.flat();

console.log(flatNumbers);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also specify the depth up to which the nested array should be flattened. The default value of the depth is 1.

For example, if you specify depth=2, JavaScript will recursively go up to two level depth to make the array flattened.

// Flatten Nested Array

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

const flatNumbers = numbers.flat(2);  // depth 2

console.log(flatNumbers);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you don’t know the depth level of the array, you can pass Infinity to the flat() method. In this case, the flat() method will recursively go up to all depth levels of the array to make it flat.

// Flatten Nested Array

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

const flatNumbers = numbers.flat(Infinity);  // Infinite depth

console.log(flatNumbers);
// Output: [1, 2, 3, 4, 5, 6, 7, 8]

2. Using the Spread operator(…)

You can also use the spread operator(...) to convert the nested array into a flattened array. The spread operator is used to unpack the elements of an array or object.

You can combine the spread operator(...) with the Array.concat() method to convert the nested array into a flat array.

See the following example:

// Flatten Nested Array

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

const flatNumbers = [].concat(...numbers);

console.log(flatNumbers);
// Output: [1, 2, 3, 4, 5, 6]

Thanks for reading.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.