Skip to content

Instantly share code, notes, and snippets.

@roshanca
Forked from ruanyf/map-vs-flatmap.js
Created January 22, 2017 04:58
Show Gist options
  • Save roshanca/cd3837c78a446c3960a8ee64393f0031 to your computer and use it in GitHub Desktop.
Save roshanca/cd3837c78a446c3960a8ee64393f0031 to your computer and use it in GitHub Desktop.
map vs. flatMap
const map = (array, func) => (
array.map(func)
);
const flatMap = (array, func) => (
array.reduce((result, element) => (
result.concat(func(element))
), [])
);
const arr = ['two birds', 'three green peas'];
const split = s => s.split(' ');
map(arr, split)
// [["two", "birds"], ["three", "green", "peas"]]
flatMap(arr, split)
// ["two", "birds", "three", "green", "peas"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment