flat() and flatMap() in JavaScript

In JavaScript, the flat() and flatMap() methods are array functions introduced in ECMAScript 2019 (ES10) for working with nested arrays. Both methods are used to flatten an array or transform and flatten it simultaneously. Here’s an explanation of each method:

  1. flat(depth): The flat() method creates a new array that is a flattened version of the original array, up to the specified depth. It recursively flattens nested arrays to the specified depth. If no depth is provided, it defaults to 1.Here’s an example to illustrate the usage of flat():
    const nestedArray = [1, 2, [3, 4, [5, 6]]];
    const flattenedArray = nestedArray.flat();
    // Output: [1, 2, 3, 4, [5, 6]]
    const deeplyFlattenedArray = nestedArray.flat(2);
    // Output: [1, 2, 3, 4, 5, 6]

    In the first example, flat() with no arguments flattens the array by one level. The nested array [3, 4, [5, 6]] is still present in the resulting array.

    In the second example, flat(2) flattens the array to a depth of 2, resulting in a completely flattened array with no nested arrays remaining.

  2. flatMap(callback): The flatMap() method applies a provided callback function to each element of the array and then flattens the result into a new array. It combines the steps of map() and flat() into a single method.Here’s an example to illustrate the usage of flatMap():
    const array = [1, 2, 3];
    const doubledAndFlattened = array.flatMap((num) => [num * 2]);
    // Output: [2, 4, 6]

    In the example, the callback function (num) => [num * 2] multiplies each element of the array by 2 and returns a new array. The resulting arrays are then automatically flattened into a single array.

Both flat() and flatMap() provide convenient ways to work with nested arrays and simplify common operations such as flattening or transforming array elements.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories