-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreduce.js
More file actions
29 lines (22 loc) · 662 Bytes
/
reduce.js
File metadata and controls
29 lines (22 loc) · 662 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var arr = [1, 2, 3, 4];
function reduceExample(arr) {
return arr.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
}
console.log("Builtin Reduce Example", reduceExample(arr));
Array.prototype.customReduce = function (callback, initialValue) {
const inputArray = this;
let output = initialValue;
for (let i = 0; i < inputArray.length; i++) {
output = callback(output, inputArray[i]);
}
return output;
};
var customReduceExample = [1, 2, 3, 4].customReduce(
(accumulator, currentValue) => {
return accumulator + currentValue;
},
0
);
console.log("Custom Reduce Example", customReduceExample);