JavaScript Array flatMap() Method

The JavaScript Array.flatMap() method first applies a mapping function to each element of the array, then flattens the result into a new array. It combines the functionality of map() and flat() into a single method, and by default, flattens the result by one level.

For example, array.flatMap(callback) is useful when you need to transform elements of an array and then flatten the result in one step.

Syntax

The syntax for the Array.flatMap() method is:

plaintext
array.flatMap(callback(element, index, array), thisArg)

Parameters

The Array.flatMap() method accepts two parameters:

  • callback (Required): A function that is executed on each element of the array. It takes the following arguments:
    • element: The current element being processed.
    • index (Optional): The index of the current element.
    • array (Optional): The array being traversed.
  • thisArg (Optional): Value to use as this when executing the callback function. If not provided, undefined is used.

Return Value

A new array with each element being the result of the callback function, flattened by one level.

Examples of JavaScript Array.flatMap() Method

Example 1: Using flatMap() to Multiply and Flatten

The flatMap() method can be used to apply a function to each element and flatten the result.

javascript
const arr = [1, 2, 3, 4];
const flatMapped = arr.flatMap(num => [num * 2]);
console.log(flatMapped);  // Output: [2, 4, 6, 8]

Explanation: The flatMap() method applies the function to multiply each number by 2, and since the result is already a single-level array, the method flattens it into [2, 4, 6, 8].

Example 2: Removing Empty Elements While Mapping

You can use flatMap() to filter out or remove unwanted elements from an array while mapping them.

javascript
const arr = ["apple", "banana", "", "cherry"];
const flatMapped = arr.flatMap(fruit => fruit ? fruit : []);
console.log(flatMapped);  

Explanation: In this example, flatMap() is used to map each element, but if the element is an empty string (""), it returns an empty array, which gets flattened and removed from the final result.

Example 3: Splitting Strings and Flattening

flatMap() can also be used to split strings into characters and then flatten the result.

javascript
const words = ["hello", "world"];
const flatMapped = words.flatMap(word => word.split(''));
console.log(flatMapped); 

Explanation: The flatMap() method splits each word into an array of characters, and then flattens the result into a single array of characters.

Example 4: Flattening and Mapping Complex Data Structures

When working with nested arrays or objects, flatMap() helps to simplify the structure.

javascript
const users = [
 { name: "Alice", hobbies: ["reading", "swimming"] },
 { name: "Bob", hobbies: ["gaming", "cycling"] }
];
const hobbies = users.flatMap(user => user.hobbies);
console.log(hobbies); 

Explanation: The flatMap() method extracts the hobbies from each user and flattens them into a single array.

Example 5: Using flatMap() with thisArg

You can provide a custom this context using the thisArg parameter.

javascript
const context = { factor: 10 };
const arr = [1, 2, 3];
const flatMapped = arr.flatMap(function(num) {
 return [num * this.factor];
}, context);
console.log(flatMapped);  // Output: [10, 20, 30]

Explanation: The thisArg parameter is used to bind the this value to the context object. The flatMap() method multiplies each number by the factor property from the context object and returns the flattened result.

Example 6: When the Result Is Already Flat

If the result of the mapping function is already flat, flatMap() still works by flattening it by one level.

javascript
const arr = [1, 2, 3];
const flatMapped = arr.flatMap(num => num);
console.log(flatMapped);  // Output: [1, 2, 3]

Explanation: The flatMap() method flattens the result by one level, even if the result of the callback function is not nested.

JavaScript

5765

761

Related Articles