The challenge was to take a simple array:
var arrays = [[1,2,3],[4,5],[6]];
And use reduce/concat to create a single array containing all values and log to the console ie [1,2,3,4,5,6] so I produced:
console.log(arrays.reduce(function(flat, current) {
return flat.concat(current);
}));
Totally works but on checking their solution they have one little difference:
console.log(arrays.reduce(function(flat, current) {
return flat.concat(current);
}, []));
What does the [ ] parameter do in the reduce function, and is it a problem that I left it out?
reduce
has the option of being passed an initial value. In their solution, they provide an empty array so the rest of your values can be added from there.
However, yours works because reduce
uses the first value in the array as the initial value if one isn't given.
From MDN (note that previousValue
is the first argument in the callback, currentValue
is the second argument):
The first time the callback is called,
previousValue
andcurrentValue
can be one of two values. IfinitialValue
is provided in the call to reduce, thenpreviousValue
will be equal toinitialValue
andcurrentValue
will be equal to the first value in the array. If noinitialValue
was provided, thenpreviousValue
will be equal to the first value in the array andcurrentValue
will be equal to the second.
Initial value.
The difference appears in two cases:
You version will crash if arrays
is empty array. Theirs won't.
If arrays
contains the single array, you get that instance, but they copy it into a new one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.