CARVIEW |
Select Language
HTTP/2 200
accept-ranges: bytes
age: 0
cache-control: public,max-age=0,must-revalidate
cache-status: "Netlify Edge"; fwd=miss
content-encoding: gzip
content-type: text/html; charset=UTF-8
date: Tue, 14 Oct 2025 09:25:59 GMT
etag: "3fd10a248d52a510018b94a56e854311-ssl-df"
server: Netlify
strict-transport-security: max-age=31536000
vary: Accept-Encoding
x-nf-request-id: 01K7H0MW9T0V2A350AEJ1RNHVW
JavaScript Array flatMap() - Mastering JS
Combining
JavaScript Array flatMap()
May 25, 2024
The flatMap()
method on JavaScript arrays combines map()
and flat()
into one call.
flatMap()
takes a callback
parameter and calls callback()
on every element in the array.
If callback
returns some value that is not an array, then flatMap()
behaves identically to map()
, adding the returned value to the result array.
const arr = ['a', 'b', 'c'];
arr.flatMap(function callback(el) {
return el.toUpperCase();
}); // ['A', 'B', 'C']
If callback
returns an array, then flatMap()
"flattens" that array and adds each element from the returned value to the result array.
const arr = [
{ title: 'Intro to JavaScript Arrays', tags: ['fundamentals', 'arrays'] },
{ title: 'Intro to Mongoose Arrays', tags: ['mongoose', 'arrays'] }
];
arr.flatMap(el => el.tags); // ['fundamentals', 'arrays', 'mongoose', 'arrays']
In the above example, flatMap()
would be useful for removing duplicates from an array of arrays:
const arr = [
{ title: 'Intro to JavaScript Arrays', tags: ['fundamentals', 'arrays'] },
{ title: 'Intro to Mongoose Arrays', tags: ['mongoose', 'arrays'] }
];
// Remove duplicate `tags` entries
[...new Set(arr.flatMap(el => el.tags)]; // ['fundamentals', 'arrays', 'mongoose']
Combining map()
and filter()
Another neat trick with flatMap()
is you can combine map()
and filter()
into one function call.
If your flatMap()
callback returns an empty array, flatMap()
won't add anything to the result array.
const numbers = [1, 2, 3, 4, 5];
// [1, 3, 5]
arr.flatMap(function filterEvenNumbers(num) {
if (num % 2 === 0) {
// returning empty array means `flatMap()` will skip this value
return [];
}
return num;
});
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!