PayPal Interview Question
Front-end Software EngineersCountry: United States
Interview Type: Phone Interview
Array.prototype.myReduce = function (callback, initValue) {
for(var i=0; i<this.length; i++){
if(initValue !== undefined){
initValue = callback(initValue, this[i], i, this)
}
else {
initValue = this[i]
}
}
return initValue;
}
console.log([1,2,3,4].myReduce((cal, val) => cal + val));
console.log([1,2,3,4].myReduce((cal, val) => cal + val, 3));
Array.prototype.myReduce = function (callback, initValue) {
for(var i=0; i<this.length; i++){
if(initValue !== undefined){
initValue = callback(initValue, this[i], i, this)
}
else {
initValue = this[i]
}
}
return initValue;
}
console.log([1,2,3,4].myReduce((cal, val) => cal + val));
console.log([1,2,3,4].myReduce((cal, val) => cal + val, 3));
Javascript .reduce example for calculating sum of an array:
The same can be written in plain JS as:
- skmohit05 December 08, 2018