menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:flat() method

menu

In JavaScript, the flat() method is a built-in array method used to flatten a nested array by removing nested subarrays and creating a new single-level array. It can also be used to specify the depth up to which you want to flatten the array. The flat() method does not modify the original array; instead, it returns a new flattened array.

Here's the basic syntax of the flat() method:

javascriptconst flattenedArray = array.flat([depth]);
  1. array: The original array that you want to flatten.

    • depth (optional): An optional integer specifying the depth to which the array should be flattened. If not provided, the default depth is 1.

If not provided, the default depth is 1. The flat() method returns a new array that is a flattened version of the original array, up to the specified depth.

Here are some examples of how the flat() method can be used:

  • Basic Flattening:

javascriptconst nestedArray = [1, [2, 3], [4, 5]];

const flattenedArray = nestedArray.flat();

console.log(flattenedArray); // Outputs: [1, 2, 3, 4, 5]

In this example, the flat() method is used to flatten a nested array, resulting in a single-level array.

  • Flattening to a Specific Depth:

javascriptconst deeplyNestedArray = [1, [2, [3, [4, [5]]]]];

const partiallyFlattenedArray = deeplyNestedArray.flat(2);

console.log(partiallyFlattenedArray); // Outputs: [1, 2, 3, [4, [5]]]

In this case, the flat(2) method is used to flatten the array up to a depth of 2, so it flattens the first two levels of nested arrays but leaves the deeper nested arrays intact.

The flat() method is especially useful when working with arrays that contain nested structures, such as arrays of arrays. It simplifies data manipulation by converting a nested structure into a flat, one-dimensional array.

1280 x 720 px