I know that the .reduce
function in Javascript has a notion of previous
and current
variables "built-in", so to speak, in its definition. So I'm curious why this doesn't work:
var bigrams = [0, 1, 2, 3, 4].reduce(function(previous, current) {
return [previous, current]
});
I do not think that means what I think it means, because now bigrams
contains:
[[[[0,1],2],3],4]
When what I wanted was:
[[0,1],[1,2],[2,3],[3,4]]
I think it has to do with the fact that the result should be pushed into the accumlator (which should perhaps be an empty array, something like: arr.reduce(/*magic*/, [])
?
- Should I not be using
.reduce
to do this? - If so, is there another "functional" way to do it?
- How do I avoid this nesting behavior?