19
May
2023
2023
flat() and flatMap() in JavaScript
by Shubham Batra
37
In JavaScript, flat() and flatMap() are array methods introduced in ECMAScript 2019 (ES10) that allow you to work with nested arrays in a concise manner. Let's explore each method:
1.) flat(): The flat() method creates a new array by concatenating all subarrays within a nested array up to a specified depth.
Syntax:
let newArray = array.flat(depth);
- Parameters:
- depth (optional): An integer specifying the depth level of flattening. If not provided, the default depth is 1.
- Example:
const nestedArray = [1, [2, 3], [4, [5, 6]]]; const flattenedArray = nestedArray.flat(); console.log(flattenedArray); // Output: [1, 2, 3, 4, [5, 6]]
In the example above, flat() is called on the nestedArray with no depth specified, resulting in a new array where subarrays are concatenated up to a depth of 1. The nested subarray [5, 6] is not flattened because the depth is 1.
2.) flatMap(): The flatMap() method combines the functionality of map() and flat() in a single step. It maps each element of an array using a mapping function and then flattens the result into a new array.
Syntax:
let newArray = array.flatMap(callback);
Parameters:
callback: A function that is called for each element in the array and returns the value to be included in the new array. It takes three arguments: currentValue, index, and array.
Example:
const numbers = [1, 2, 3, 4, 5]; const doubledArray = numbers.flatMap(num => [num, num * 2]); console.log(doubledArray); // Output: [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]
In the example above, flatMap() is used to create a new array where each element of the original array is mapped to two elements: the original value and its double.
It's important to note that both flat() and flatMap() methods are non-mutating, meaning they do not modify the original array. Instead, they return a new array with the desired transformation applied.