JavaScriptArrays
Array. prototype. flatMap()
Maps every element and flattens the result by one level.
- Returns
- A new array of the results, flattened by one level.
- Changes the original
- No
Example
#JavaScript
const courses = [
{ name: 'HTML', tags: ['web', 'basics'] },
{ name: 'Python', tags: ['data', 'ai'] }
]
console.log(courses.flatMap((course) => course.tags))Console
['web', 'basics', 'data', 'ai']
Definition and usage
#The flatMap() method combines map() and flat() in a single step. The function can return an array, and its elements get inserted directly into the result.
That means one element can turn into several elements, or into none at all (when the function returns an empty array). It’s a convenient way to transform and filter data at the same time.
Flattening only works one level deep. If the function returns arrays nested deeper than that, the rest stays nested.
Syntax
#Syntax
array.flatMap(callbackFn)
array.flatMap(callbackFn, thisArg)Parameters
#callbackFn
function (element, index, array)
A function that returns a value, or an array of values.thisArg
optional
Thethisvalue inside the function.
More examples
#JavaScript
const inputs = ['12', 'abc', '7', '']
const numbers = inputs.flatMap((value) => {
const n = Number.parseInt(value, 10)
return Number.isNaN(n) ? [] : [n]
})
console.log(numbers)Console
[12, 7]
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Returning
[]from the function removes an element from the result, and[a, b]turns one element into two. - When you don’t need flattening, a plain
map()is clearer.
Related entries
#Spotted a mistake or missing an example? Write to us.