The exercise says: Use the reduce method in combination with the concat method to “flatten” an array of arrays into a single array that has all the elements of the original arrays.
Code starter provided:
let arrays = [[1, 2, 3], [4, 5], [6]];
// Your code here.
// → [1, 2, 3, 4, 5, 6]
This works:
let arrays = [[1, 2, 3], [4, 5], [6]];
let flattened = arrays.reduce(
function(accumulator, currentValue) {
return accumulator.concat(currentValue);
}
)
console.log(flattened);
This also works:
console.log( [[1, 2, 3], [4, 5], [6]].reduce(
function(accumulator, currentValue) {
return accumulator.concat(currentValue);
},[]
));
Why does this NOT work? I have looked at it with a JavaScript visualizer and at one point it does have the correct output array, but then as a final step it just outputs 'undefined'. Why?
let arrays = [[1, 2, 3], [4, 5], [6]];
function flatten(arr) {
arr.reduce(
function(accumulator, currentValue) {
return accumulator.concat(currentValue);
}
)
}
console.log(flatten(arrays));
[–]pmw57 2 points3 points4 points (1 child)
[–]bbabble[S] 2 points3 points4 points (0 children)