After spending hours reading and watching videos to understand the reduce function, I finally had a breakthrough. It wasn't until I took a break, made some food, and came back to my computer that it all clicked. Now, I confidently grasp how the reduce function works.
However, I still find myself puzzled by why the first example below functions correctly while the second one does not.
Source: Eloquent Javascript Ch. 5 §Flattening
This code snippet works:
var arrays = [[1, 2, 3], [4, 5], [6]];
var flattened = arrays.reduce(function(a, b) {
return a.concat(b);
});
flattened; //=>[1, 2, 3, 4, 5, 6]
I attempted to modify the code by turning the variable into a function, only to encounter an issue. The following code snippet returns undefined
, leaving me uncertain about what went wrong:
This code snippet doesn't work:
var arrays = [[1, 2, 3], [4, 5], [6]];
function flattened(arr){
arr.reduce(function(a, b) {
return a.concat(b);
});
}
flattened(arrays); //=> undefined
Curious as to why the first approach is successful while the second one fails, I suspect there might be a minor detail that has eluded my understanding.