JavaScript Array flat() method


The flat() method in JavaScript is used to create a new array with all sub-array elements concatenated into it recursively up to a specified depth. This method is particularly useful for flattening nested arrays, allowing you to reduce the depth of nested structures in a straightforward manner.

Syntax:

let newArray = array.flat(depth);
  • depth (optional): A non-negative integer that specifies how deep a nested array structure should be flattened. The default is 1, which means only the first level of nested arrays will be flattened. If omitted, it flattens one level by default.

Return Value:

  • A new array that is a flattened version of the original array, with elements from sub-arrays merged into it.

Key Points:

  • The flat() method does not modify the original array; it returns a new array instead.
  • If depth is set to Infinity, it will recursively flatten the array regardless of how deeply nested it is.
  • Non-array items are included as-is in the new array.

Example 1: Basic usage

let array = [1, 2, [3, 4]]; let flattened = array.flat(); // Flatten one level console.log(flattened); // [1, 2, 3, 4]

Example 2: Specifying depth

let array = [1, 2, [3, 4, [5, 6]]]; let flattened = array.flat(1); // Flatten one level console.log(flattened); // [1, 2, 3, 4, [5, 6]] flattened = array.flat(2); // Flatten two levels console.log(flattened); // [1, 2, 3, 4, 5, 6]

Example 3: Flattening deeply nested arrays

let array = [1, [2, [3, [4, [5]]]]]; let flattened = array.flat(Infinity); // Flatten all levels console.log(flattened); // [1, 2, 3, 4, 5]

Example 4: Non-array elements

let array = [1, 2, [3, 4], 5]; let flattened = array.flat(); // Flatten one level console.log(flattened); // [1, 2, 3, 4, 5]

Example 5: Empty arrays

let array = [1, 2, [], 3, [4, 5, []]]; let flattened = array.flat(); // Flatten one level console.log(flattened); // [1, 2, 3, 4, 5]

Summary:

  • The flat() method provides an easy way to flatten nested arrays into a single array, which can simplify data structures for processing.
  • It is especially useful when working with data that can have variable levels of nesting, making it easier to handle in various applications.
  • Since it creates a new array, the original structure remains unchanged, allowing for flexibility in manipulating data.