JavaScript Array flatMap: Map and Flatten Arrays
The Array.prototype.flatMap() method in JavaScript
provides an efficient way to transform and flatten collections in a
single operation. It combines the functionality of
Array.prototype.map() followed by
Array.prototype.flat() with a depth of 1. This method
allows developers to map each element to a new value or sub-array and
immediately flatten the resulting structure, eliminating the performance
overhead of creating intermediate arrays.
How flatMap() Works
The flatMap() method executes a provided callback
function once for each element in the array. The callback returns a
value, which can be a single item or an array. Once all elements are
mapped, flatMap() flattens the resulting array of arrays
into a new, single-dimensional array at depth 1.
const numbers = [1, 2, 3, 4];
// Mapping each number to a pair, then flattening
const result = numbers.flatMap(num => [num, num * 2]);
console.log(result);
// Output: [1, 2, 2, 4, 3, 6, 4, 8]Under the hood, flatMap() is functionally equivalent to
calling arr.map(...args).flat(1), but it is more efficient
because it handles both tasks in one iteration.
Key Use Cases
1. Splitting Strings and Combining Results
flatMap() is ideal for extracting and combining items
from structured text or tokenized lists.
const sentences = ["Hello world", "JavaScript is awesome"];
const words = sentences.flatMap(sentence => sentence.split(" "));
console.log(words);
// Output: ["Hello", "world", "JavaScript", "is", "awesome"]2. Filtering and Mapping Simultaneously
Since an empty array [] flattens into nothing, you can
use flatMap() to conditionally filter out items while
transforming others. This avoids chaining .filter() and
.map().
const transactions = [10, -5, 20, -1, 30];
// Keep only positive numbers and format them
const positiveFormatted = transactions.flatMap(amount =>
amount > 0 ? [`$${amount}`] : []
);
console.log(positiveFormatted);
// Output: ["$10", "$20", "$30"]3. Expanding One-to-Many Relationships
When working with nested relational data (such as users with lists of
orders), flatMap() extracts child items into a uniform
list.
const users = [
{ name: "Alice", tasks: ["Design", "Test"] },
{ name: "Bob", tasks: ["Deploy"] }
];
const allTasks = users.flatMap(user => user.tasks);
console.log(allTasks);
// Output: ["Design", "Test", "Deploy"]Important Limitations
- Flatten Depth:
flatMap()only flattens to a depth of 1. If your callback returns arrays that are nested multiple levels deep, any inner arrays beyond the first level will remain intact. - Immutability: Like standard
map(),flatMap()does not mutate the original array; it returns a new array containing the flattened elements.