Javascript: Exercise With Concat And Reduce
I'm working on an exercise where, starting from an array of arrays, I have to reduce it (using reduce and concat) in a single array that contains all the elements of every single a
Solution 1:
i not have completely clear how reduce works yet
It works like this:
Array.prototype.reduce = function(callback, startValue){
var initialized = arguments.length > 1,
accumulatedValue = startValue;
for(var i=0; i<this.length; ++i){
if(i inthis){
if(initialized){
accumulatedValue = callback(accumulatedValue, this[i], i, this);
}else{
initialized = true;
accumulatedValue = this[i];
}
}
}
if(!initialized)
thrownewTypeError("reduce of empty array with no initial value");
return accumulatedValue;
}
Your failing example does pretty much this:
vararray = [[1,2,3],[4,5,6],[7,8,9]];
var tmp = 0;
//and that's where it fails.//because `tmp` is 0 and 0 has no `concat` method
tmp = tmp.concat(array[0]);
tmp = tmp.concat(array[1]);
tmp = tmp.concat(array[2]);
var new_array = tmp;
replace the 0
with an Array, like [ 0 ]
Post a Comment for "Javascript: Exercise With Concat And Reduce"