rashmi agar
30 posts
Mar 08, 2025
10:35 PM
|
javascript flatmap method is a powerful tool for working with arrays, combining mapping and flattening in a single step. It is particularly useful when you want to transform an array and remove nesting in one go.
What is flatMap()? The flatMap() method first maps each element using a mapping function and then flattens the result by one level. It is essentially a shortcut for calling .map() followed by .flat(1).
Syntax: javascript Copy Edit const newArray = array.flatMap(callback(element, index, array), thisArg); callback: A function to execute on each element of the array. thisArg (optional): Value to use as this inside the callback function. Example Usage: 1. Flattening an array of arrays: javascript Copy Edit const arr = [[1], [2], [3]]; const result = arr.flatMap(x => x); console.log(result); // Output: [1, 2, 3] 2. Transforming and flattening in one step: javascript Copy Edit const words = ["hello", "world"]; const result = words.flatMap(word => word.split("")); console.log(result); // Output: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] When to Use flatMap()? When mapping and flattening are both needed. When dealing with nested arrays that need to be processed and reduced to a simpler form. When improving performance over .map().flat(1). Caveats: flatMap() only flattens one level. If you need deeper flattening, you still need to use .flat(Infinity). It does not modify the original array but returns a new one.
|