I am trying to understand the raw codes of the reduce function and how to use it.
var each = function(collection, callback){
if(Array.isArray(collection)){
for(var i=0;i<collection.length;i++){
callback(collection[i]);
}
}
else{
for(var key in collection){
callback(collection[key]);
}
}
};
var reduce = function(collection, callback, accumulator){
each(collection, function(element){
if(accumulator === undefined) {
return accumulator = element;
}else {
return accumulator = callback(accumulator, element);
};
});
return accumulator;
};
var sArr = [3, 2, 3, 4, 5];
each(sArr, function(collection){
console.log(collection);
});
reduce(sArr, function(collection, prev){
console.log(prev = prev + sArr);
});
On my codes above as you can see I was trying to reduce all of my arrays into one element by adding them all up just like a normal reduce function does but it doesn't work the way I think it is.
Can somebody check if I am doing wrong and if you can explain to me in layman's term what does my reduce function does line by line?
Sorry newbie.
reducefunction to actually return a value at the end)ReferenceError: myArr is not defined. Make sure what you're testing is actually what you posted. :)