In JavaScript, arrays are one of the most commonly used data structures. They can become complex, especially when dealing with nested arrays. Two array methods that are particularly useful for handling nested arrays are flat()
and flatMap()
. These methods, introduced in ES2019, offer elegant solutions for flattening arrays and mapping over arrays, then flattening the result. This article will delve into the details, differences, and practical applications of flat()
and flatMap()
, along with illustrative code examples.
The flat()
Method
What is flat()
?
The flat()
method creates a new array with all sub-array elements concatenated into it recursively up to a specified depth.
var newArray = arr.flat([depth]);
arr
: The array to flatten.depth
(optional): The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
Example 1: Basic Usage
let nestedArray = [1, [2, 3], [4, [5, 6]]];
let flattenedArray = nestedArray.flat();
console.log(flattenedArray); // Output: [1, 2, 3, 4, [5, 6]]
Example 2: Specifying Depth
let nestedArray = [1, [2, [3, [4, 5]]]];
let flattenedArray =…