JavaScript Array flatMap() method


The flatMap() method in JavaScript is a combination of the map() and flat() methods. It first maps each element using a provided mapping function and then flattens the result into a new array. This method is useful for applying a transformation to each element and simultaneously flattening the result, particularly when the mapping function returns an array.

Syntax:

let newArray = array.flatMap(callback(currentValue[, index[, array]])[, thisArg]);
  • callback: A function that is called for each element in the array. It takes three arguments:
    • currentValue: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array that flatMap was called upon.
  • thisArg (optional): A value to use as this when executing the callback.

Return Value:

  • A new array with the results of the callback function mapped and flattened.

Key Points:

  • The flatMap() method first maps each element to a new value and then flattens the resulting array to a depth of 1.
  • It does not modify the original array; instead, it returns a new array.
  • If the mapping function returns a non-array value, that value will still be included in the resulting array as-is.

Example 1: Basic usage

let array = [1, 2, 3]; let result = array.flatMap(x => [x * 2]); console.log(result); // [2, 4, 6]

Example 2: Returning arrays from the callback

let array = [1, 2, 3]; let result = array.flatMap(x => [x, x * 2]); console.log(result); // [1, 2, 2, 4, 3, 6]

Example 3: Flattening nested structures

let array = [1, 2, 3]; let result = array.flatMap(x => [[x], [x * 2]]); // Each element maps to an array of arrays console.log(result); // [1, 2, 2, 4, 3, 6]

Example 4: Using objects

let array = [{ id: 1 }, { id: 2 }]; let result = array.flatMap(item => [item.id]); console.log(result); // [1, 2]

Example 5: Handling empty results

let array = [1, 2, 3]; let result = array.flatMap(x => (x > 1 ? [x] : [])); // Only include elements greater than 1 console.log(result); // [2, 3]

Summary:

  • The flatMap() method provides a convenient way to map an array's elements to new values and flatten the results in a single step.
  • This method is particularly useful when each mapped element could generate multiple values (i.e., arrays) and you want to combine the results into a single array.
  • It simplifies code by reducing the need for separate mapping and flattening operations.