Skip to content

Instantly share code, notes, and snippets.

@subhaze
Created April 22, 2016 14:25
Show Gist options
  • Save subhaze/733586836a4c3ec00c97661abf301962 to your computer and use it in GitHub Desktop.
Save subhaze/733586836a4c3ec00c97661abf301962 to your computer and use it in GitHub Desktop.
flatMap [Array#reduce]
<pre style="padding: 20px"><code class="hljs js">
let stuff = ['a', 'b', 'c', ['e', 'f', 'g']];
function flatMap(list, projection){
return list.reduce( (acc, curr) =>
Array.isArray(curr)
? acc.concat(curr.map(projection))
: acc.concat(projection(curr))
, []);
}
console.log(flatMap(stuff, (x)=>x+'1'));
// ["a1", "b1", "c1", "e1", "f1", "g1"]
</code></pre>
let stuff = ['a', 'b', 'c', ['e', 'f', 'g']];
function flatMap(list, projection){
return list.reduce( (acc, curr) =>
Array.isArray(curr)
? acc.concat(curr.map(projection))
: acc.concat(projection(curr))
, []);
}
console.log(flatMap(stuff, (x)=>x+'1'));
// ["a1", "b1", "c1", "e1", "f1", "g1"]
hljs.initHighlightingOnLoad();
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/tomorrow-night-eighties.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment