Skip to main content

Command Palette

Search for a command to run...

Flatten the Chaos: Mastering Array Flattening in JavaScript

From Nested Nightmares to Clean Lists — Smart Techniques Every Developer Should Know

Updated
5 min read
Flatten the Chaos: Mastering Array Flattening in JavaScript

Array Flatten means flatten an nested Array. But what is a Nested Array? Let’s discuss it first.

Nested Array

A array is a collection of the elements, and a Nested Array are array inside array. Nested Array have one or more array elements as the element of an array. Let’s take an example

let arr = ["Sydney", "Lods", "Capetown", ["Kolkata", "Mumbai", "Chennai", "Delhi"]];

In the example we can see that first 3 elements are in normal string but the last element is an array of string again. We can add multiple arrays as an element.

let arr = ["Sydney", "Lods", "Capetown", ["Kolkata", "Mumbai", "Chennai", "Delhi"]];

console.log(arr);
console.log("Type of array is: ", typeof (arr));

The output will become

[
  'Sydney',
  'Lods',
  'Capetown',
  [ 'Kolkata', 'Mumbai', 'Chennai', 'Delhi' ]
]
Type of array is:  object

Why Nested Array?

Key reasons for using a nested array

  • They are essential for creating tree like structure, such as dictionary, menu etc.

  • They act as matrix or grids for mathematical computation or game board.

  • They allow paring related separate element together within a single list.

  • They offer the flexibility to nest arrays inside objects or vice versa to structure complex API responses or JSON data.

Array Flatten

Array flatten is a method in JavaScript involves combining multiple nested arrays into a single level array. This process involves iterating through each nested array and appending its elements to a new array, resulting in a flattened structure.

Why Flatten Array ?

Flatten Array simplifies complex data structure into a manageable list, eliminating the need for nested loops while improving code readability and performance.

  • Linear array are easier to iterate through using simple methods like map() , filter() , reduce() .

  • Data from APIs often comes grouped, but frontend UIs or reporting tools require a flat, singular list.

  • It makes complex algorithmic operations, such as depth-first searches or data transformation, much cleaner and more predictable.

  • Flattening allows for cleaner mapping of data to UI components.

How to Flatten an Array ?

Using array.flat() method

We can merge the array using the array.flat() method. This method creates a new array with all subarray element concatenate to it. The syntax is

array.flat(depth)

Here the depth is optional. It means how much deep a nested array should be flattened. Default value is 1.

Here is an example,

let arr = ["Sydney", "Lods", "Capetown", ["Kolkata", "Mumbai", "Chennai", "Delhi"]];
const newArray = arr.flat();

console.log("Old Array: ", arr);
console.log("New Array: ", newArray);

The output will be

Old Array:  [
  'Sydney',
  'Lods',
  'Capetown',
  [ 'Kolkata', 'Mumbai', 'Chennai', 'Delhi' ]
]
New Array:  [
  'Sydney',   'Lods',
  'Capetown', 'Kolkata',
  'Mumbai',   'Chennai',
  'Delhi'
]

Here the default depth value is 1 and the array also has only one depth.

If we want to flatten the array to any depth we will use Infinity inside the depth.

let arr = [10, 20, [30, 40], [50, 60, [70, 80, 90], 100], 110, 120];
const depth1 = arr.flat();
const fullFlat = arr.flat(Infinity);

console.log("Old Array: ", arr);
console.log("Dpeth 1 Array: ", depth1);
console.log("Full Flatten Array: ", fullFlat);

The Output will become

Old Array:  [ 10, 20, [ 30, 40 ], [ 50, 60, [ 70, 80, 90 ], 100 ], 110, 120 ]
Dpeth 1 Array:  [ 10, 20, 30, 40, 50, 60, [ 70, 80, 90 ], 100, 110, 120 ]
Full Flatten Array:  [
   10,  20, 30, 40,  50,
   60,  70, 80, 90, 100,
  110, 120
]

Here when we use only flat it just go to depth 1 and flatten and rest of nested array of more depth remain same as it is.

But when we use Infinity as depth then no matter how deeper the nested array is it just flat everything into a single array.

array.concat() method

Here we use the spread operator to spread the value and then use the array.concat() method to merge them up into a single array.

let arr1 = [10, 20, [30, 40], [50, 60, [70, 80, 90], 100], 110, 120];
let arr2 = ["Sydney", "Lods", "Capetown", ["Kolkata", "Mumbai", "Chennai", "Delhi"]];

const newArr1 = [].concat(...arr1);
const newArr2 = [].concat(...arr2);
console.log("New Array1: ", newArr1);
console.log("New Array2: ", newArr2);

The output will be:

New Array1:  [ 10, 20, 30, 40, 50, 60, [ 70, 80, 90 ], 100, 110, 120 ]
New Array2:  [
  'Sydney',   'Lods',
  'Capetown', 'Kolkata',
  'Mumbai',   'Chennai',
  'Delhi'
]

In the output we can clearly see that it only flatten the array only to a single level.

Custom Recursive function

We can built our custom recursive function to flatten the array in any process.

Final thoughts

Flatten an array is an important concept in JavaScript many times used in to flat an API response. Mostly array.flat(Infinity) used to flat an array where we don’t need to think of the depth of the array. It does its job automatically.

Reference Article

You can follow the following articles for more understanding

That's it, now you understand How to Flatten an array in JavaScript. I’d love to hear your thoughts and feedbacks.

Thank You for your patients. ❤️