A quick real life example would be, maybe you have an image as an array and then a function that returns a color for each pixel (length 3 array, rgb) and you want to write it to a file, which is just a single stream of numbers.
Then you could `image.flatMap(getColor)` and get a 1d array that looks like rgbrgbrgbrgb..., perfect for writing to files.
A more theoretical example is, using Arrays to represent uncertainty:
A dice roll could be written as the array `dice = [1,2,3,4,5,6]`, meaning "any of these values with equal likelyhood".
So then what's the sum of two dice rolls?
`dice.flatMap(a => dice.map(b => a+b));`
And the resulting array is all possible sums you can roll, with equal likelyhood.
Hope those examples were somewhat clear!
There's also a really deep and awesome connection between Arrays/flatMap and Promises/await but I'd need a few pages to explain (monads).
From the looks of it, flatMap is essentially just a way of using the map function more efficiently when creating a new array. Generally, when only working with the map function, you'll be left with something like this:
var arr = [5,9,3];
arr = arr.map(x => [x*2]);
// Output: [,,]
To avoid having to deal with every individual element as its own unique array, the flatMap function will essentially just keep the array looking "normal", so to speak:
var arr = [5,9,3];
arr = arr.flatMap(x => [x*2]);
// Output: [10,18,6]
This was a good resource I found for it if you're looking to read into the function a little further:
Sonic Not for all of them in general no but for special cases.
That's the direction Monads are going in.
.flatMap() has two parameters, an Array (before the dot) and a function that produces Arrays.
It does essentially two things:
- "Unpack" individiual elements from the array, so the function we pass along can take them, that's the mapping part
- Merge the two layers of arrays into one, that's the flattening part (what Faisal was saying)
If those two general steps define flatMapping we can apply the same concept to Promises' .then():
- It unpacks a promise by waiting for it to resolve, before passing it to the function you supply
- That function can also return a promise, which means we have a promise inside a promise but .then() flattens it into just one promise.
So .then() is just a flatMap.
Turns out you can define flatMap for a lot of datatypes/records/structs, and a datatype + flatMap + minor technicalities = a monad.
I'm running out of space so no more examples sorry