समस्या
हमें एक JavaScript फ़ंक्शन लिखना है जो एक सरणी, एक कॉलबैक फ़ंक्शन और एक प्रारंभिक मान लेता है।
फ़ंक्शन को सरणी के पुनरावृत्ति पर एक मान संचय करना चाहिए और अंत में मान वापस करना चाहिए जैसे Array.prototype.reduce() करता है।
उदाहरण
कोड निम्न है -
const arr = [1, 2, 3, 4, 5];
const sum = (a, b) => a + b;
Array.prototype.customReduce = function(callback, initial){
if(!initial){
initial = this[0];
};
let res = initial;
for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){
res = callback(res, this[i]);
};
return res;
};
console.log(arr.customReduce(sum, 0));
आउटपुट
कंसोल आउटपुट निम्न है -
15