Flat and flatMap methods

 Flat and flatMap methods


The flat and flatMap methods are new array methods added in ECMAScript 2019 that allow you to work with nested arrays more easily. The flat() method returns a new array with all sub-array elements concatenated into it recursively up to the specified depth. The flatMap() method is similar to the map() method, but it also flattens the result array. Here's an example:


const myArray = [1, [2, 3], [4, [5, 6]]];

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


const mappedAndFlattenedArray = myArray.flatMap(num => [num * 2]);

console.log(mappedAndFlattenedArray); // Output: [2, 4, 6, 8, 10, 12]




In the code above, we're using the `flat()` method to flatten a nested array, and the `flatMap()` method to map and flatten an array at the same time.


No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...