Calls a function on each element of an array, then flattens the result into a new array. This is identical to a map followed by flat with depth 1.
flatMap(callback, thisArg?)
callback function(value, index, array)
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg optional
An object to which the this keyword refers in the callback function. If thisArg is omitted, undefined is used instead.
A new array.
[2, 3, 4, 5, 6].flatMap(x => [x, 2**x])
[2, 4, 3, 8, 4, 16, 5, 32, 6, 64]
var prices = {
"tea": 2,
"coffee": 5
}
Object.entries(prices).flatMap(([name, price]) => [name, '$'+price]).join(' ')
"tea $2 coffee $5"