Table of Contents

JavaScript Array flatMap() Method is used to transform each element of an array and flatten the resulting array by one level. It combines the functionality of map() and flat() into a single operation.

It is useful when a callback returns multiple values for each original element and you want to combine them into one array.

const numbers = [1, 2, 3];

const result = numbers.flatMap(number => [number, number * 2]);

console.log(result);

Output:

[1, 2, 2, 4, 3, 6]

Each number produces two values. The resulting nested arrays are flattened by one level.

JavaScript Array flatMap() Method Syntax

The syntax of flatMap() is:

array.flatMap(callbackFn);

Parameter:

  • callbackFn: A function executed for every element. It receives three arguments:
    • currentValue: The current array element.
    • index: The current element’s index.
    • array: The original array being processed.

Return Value:

The method returns a new array containing the callback results flattened by one level. The original array is not modified.

Mechanics of the Two-Step Operation

The name flatMap() is an exact descriptor of its internal execution sequence: it performs a .map() operation first, followed immediately by a .flat(1) operation on the resulting structure. However, executing both steps in a single method call is more efficient than chaining them separately because the JavaScript engine does not need to allocate memory for an intermediate nested array before flattening it.

Consider a scenario where you want to transform a set of numbers by multiplying each value by two, while also returning the original value alongside the multiplied value.

JavaScript

const numbers = [1, 2, 3];

// Using flatMap to map each number to an array containing [original, doubled]
const expanded = numbers.flatMap(num => [num, num * 2]);

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

Behind the scenes, the callback function returns an array for every single iteration:

  • For 1, it returns [1, 2]

  • For 2, it returns [2, 4]

  • For 3, it returns [3, 6]

The resulting unflattened array would normally look like [[1, 2], [2, 4], [3, 6]]. Because flatMap() automatically applies a flattening depth of 1, the nested brackets are stripped away, yielding a single flat array containing all six elements in sequential order.

Expanding Array Elements Dynamically

One of the most versatile capabilities of flatMap() is its ability to change the cardinality of an array. While standard .map() maintains a strict one-to-one mapping relationship—meaning the output array always has the exact same number of elements as the input array—flatMap() allows a single input element to expand into zero, one, or multiple output elements.

This dynamic expansion is especially useful when parsing text, splitting strings, or working with hierarchical data structures where items need to be broken down.

JavaScript

const sentences = [
  "JavaScript is versatile",
  "Array methods are powerful"
];

// Split every sentence into individual words
const words = sentences.flatMap(sentence => sentence.split(" "));

console.log(words);
// Output: ["JavaScript", "is", "versatile", "Array", "methods", "are", "powerful"]

In this example, the sentence.split(" ") call returns a variable-length array of words for each sentence string. flatMap() takes these individual word arrays and seamlessly integrates them into a single continuous array of strings.

Simultaneous Filtering and Mapping Operations

Because flatMap() automatically flattens arrays of depth 1, you can leverage it to filter out unwanted elements while simultaneously transforming the retained items in a single pass. If the callback function returns an empty array [] for a specific element, flattening that empty array contributes zero elements to the final output, effectively acting as a filter.

JavaScript

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

// Double even numbers, and completely discard odd numbers
const processed = numbers.flatMap(num => {
  if (num % 2 === 0) {
    return [num * 2]; // Returns an array with the transformed value
  }
  return []; // Returns an empty array, which flattens into nothing
});

console.log(processed);
// Output: [4, 8, 12]

This pattern replaces the common functional chain of arr.filter(...).map(...) with a single unified iteration step, reducing redundant array traversals when processing large data sets.

Comparing flatMap() with Chained map().flat()

To fully appreciate the design of flatMap(), it is helpful to contrast it directly with chaining the individual map() and flat() methods together. Syntactically and logically, arr.flatMap(callback) produces the exact same output as arr.map(callback).flat(1).

JavaScript

const values = [1, 2, 3];

// Chained approach
const chainedResult = values.map(x => [x, x * 10]).flat(1);

// Unified flatMap approach
const flatMapResult = values.flatMap(x => [x, x * 10]);

console.log(chainedResult);  // [1, 10, 2, 20, 3, 30]
console.log(flatMapResult);  // [1, 10, 2, 20, 3, 30]

Despite producing identical outputs, flatMap() has structural advantages:

  1. Conciseness: It requires less boilerplate syntax and eliminates the need to specify a flattening depth argument.

  2. Optimization: JavaScript engines can optimize a single flatMap iteration much more effectively than allocating an intermediate array structure during a separate .map() call before running .flat().

Behavior with Sparse Arrays and Missing Indices

When executing flatMap() on sparse arrays—arrays containing empty slots or missing indices—the method exhibits specific rules regarding how it treats those gaps.

If an array has empty slots, the callback function is not called for those empty indices. Furthermore, if the callback function returns an array, any empty slots or undefined elements within that returned inner array are preserved or handled according to standard flattening rules, but missing slots in the source array are skipped entirely.

JavaScript

const sparseArray = [1, , 3]; // Index 1 is an empty slot

const result = sparseArray.flatMap(x => [x, x * 2]);

console.log(result);
// Output: [1, 2, 6] (Notice that the empty slot at index 1 is completely omitted)

Additionally, flatMap() is strictly limited to a flattening depth of 1. Unlike the standalone .flat(depth) method, which accepts any integer depth or Infinity to flatten deeply nested structures recursively, flatMap() cannot flatten arrays nested beyond a single level of depth. If your callback function returns multi-dimensional arrays nested two or more levels deep, flatMap() will only unwrap the outermost layer.

JavaScript

const nestedData = [1, 2];

// Returning a nested array two levels deep
const deepResult = nestedData.flatMap(x => [[x * 10]]);

console.log(deepResult);
// Output: [[10], [20]] — The outer array from map is flattened, but the inner array remains nested

Utilizing the Optional thisArg Execution Context

The second parameter of the flatMap() method, thisArg, allows you to define a specific object context that will be referenced by the keyword this inside the callback function. This is particularly useful when writing object-oriented codebases or when passing utility methods that rely on internal object state without needing to manually bind the function context using .bind(this) or capture variables in closure scopes.

JavaScript

const multiplierConfig = {
  factor: 10,
  multiply(value) {
    return value * this.factor;
  }
};

const numbers = [1, 2, 3];

// Passing 'multiplierConfig' as the second argument (thisArg)
const scaled = numbers.flatMap(function(num) {
  return [num, this.multiply(num)];
}, multiplierConfig);

console.log(scaled);
// Output: [1, 10, 2, 20, 3, 30]

If you use arrow functions for the callback, the thisArg parameter has no effect because arrow functions lexically bind their this value from the enclosing execution scope. However, when using standard anonymous or named function expressions, thisArg provides a clean mechanism for injecting context configurations directly into the array transformation lifecycle.