iteration using reduce method in javascript code example
Example 1: reduce object to array javascript
var arr = [{x:1},{x:2},{x:4}];
arr.reduce(function (a, b) {
return {x: a.x + b.x};
})
arr.reduce((a, b) => ({x: a.x + b.x}));
Example 2: reduce method javascript
const array1 = [1, 2, 3, 4];
const callback = (accumulator, currentValue) => accumulator + currentValue;
console.log(array1.reduce(callback));
console.log(array1.reduce(callback, 5));
Array.prototype.myReduce = function(callback, acc) {
if (!acc) {
acc = this.shift();
}
this.forEach(function(element) {
acc = callback(acc, element)
})
return acc;
}