Skip to content

Instantly share code, notes, and snippets.

@ruanyf
Created January 19, 2017 10:47
Show Gist options
  • Save ruanyf/d7141535fe0442ab7766d63617484160 to your computer and use it in GitHub Desktop.
Save ruanyf/d7141535fe0442ab7766d63617484160 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