🧑💻 Custom Reduce Function
Array Reduce
function arrayReduce(arr, func, initial) {
let result = initial;
arr.forEach((val) => {
result = (result === undefined) ? val : func(result, val);
});
return result;
}
const arr = [1, 2, 3, 4, 5];
const sum = arrayReduce(arr, (result, val) => result + val);
const prod = arrayReduce(arr, (result, val) => result * val, 2);
console.log(sum, prod);
Output:
15 240
Object Reduce
function objectReduce(obj, func, initial, ownPropertiesOnly = true) {
let result = initial;
for (const key in obj) {
if (!ownPropertiesOnly || obj.hasOwnProperty(key)) {
result = func(result, key, obj[key]);
}
}
return result;
}
const result = objectReduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, key, value) {
(result[value] || (result[value] = [])).push(key);
return result;
}, {});
console.log(result);
Output:
{ '1': [ 'a', 'c' ], '2': [ 'b' ] }