JSFiddle - React, Tailwind, and code Playground
JavaScript
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue, index, array) => {
return accumulator + currentValue
};
// 1 + 2 + 3 + 4
/* console.log(array1.reduce(reducer)); */
// expected output: 10
// 5 + 1 + 2 + 3 + 4
/* console.log(array1.reduce(reducer, 5)); */
// expected output: 15
Array.prototype.c_reduce = function(cb, initialValue) {
let accumulator = initialValue ? initialValue : this[0];
for (let i = 1; i < this.length; i++) {
accumulator = cb(accumulator, this[i], i, this)
}
return accumulator
}
console.log(array1.c_reduce(reducer))