flatMap()

ES2019+

Returns a new array formed by applying a given callback function to each element of the array, then flattening the result by one level.

Syntax

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

Parameters

callback Function

Function that produces an element of the new Array

Return Value

Array

A new array with mapped and flattened elements

Examples

JavaScript
const sentences = ['Hello World', 'How are you'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words);
Output:
// ['Hello', 'World', 'How', 'are', 'you']

📌 When to Use

Use flatMap() when you need to map elements to arrays and then flatten the result by one level. It's perfect for one-to-many transformations, like splitting strings into words or expanding items with their variations.

⚠️ Common Mistakes

Forgetting that flatMap() only flattens one level - not suitable for deep flattening

Using map().flat() when flatMap() would be cleaner and slightly more efficient

Returning non-array values from the callback - they will be wrapped in an array

✅ Best Practices

Return an empty array [] to filter out elements: arr.flatMap(x => x.valid ? [x] : [])

Use flatMap() instead of map().flat(1) for better performance

Combine filter and map in one pass: arr.flatMap(x => condition ? [transform(x)] : [])

⚡ Performance Notes

flatMap() is more efficient than map().flat() because it only iterates once. It's O(n*m) where n is the array length and m is the average length of mapped arrays. For filter+map operations, flatMap with conditional returns is faster than chaining.

🌍 Real World Example

Extracting All Words from Sentences

Split an array of sentences into a flat array of all words

const sentences = [
  'Hello world',
  'JavaScript is awesome',
  'Learn to code'
];

const allWords = sentences.flatMap(sentence =>
  sentence.split(' ')
);
// ['Hello', 'world', 'JavaScript', 'is', 'awesome', 'Learn', 'to', 'code']

// Filter and map in one pass - get valid emails from users
const users = [{email: 'a@b.com', active: true}, {email: null, active: true}, {email: 'c@d.com', active: false}];
const activeEmails = users.flatMap(user =>
  user.active && user.email ? [user.email] : []
);
// ['a@b.com']

Related Methods