Implement reduce in javascript
Reducing an array to a single value
Often we have to iterate over the array by accessing multiple items at a time. For example, if you have to find the largest element in an array, then you have to keep track of the largest value in a closure while iterating over it. This behavior can be abstracted using Array.prototype.reduce()
.
This post is a follow up post of the
- Getting started Functional Programming in JavaScript. I would recommend reading that post first.
Problem
Find the maximum element in the given array
Let's solve with
Array.prototype.forEach()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function reduce() { | |
var boxarts = [{ | |
width: 200, | |
height: 200 | |
}, { | |
width: 150, | |
height: 200 | |
}, { | |
width: 300, | |
height: 200 | |
}, { | |
width: 425, | |
height: 150 | |
}], | |
currentSize, | |
maxSize = -1, | |
largestBoxart; | |
boxarts.forEach(function(boxart) { | |
currentSize = boxart.width * boxart.height; | |
if (currentSize > maxSize) { | |
largestBoxart = boxart; | |
maxSize = currentSize; | |
} | |
}); | |
return largestBoxart; | |
} | |
console.log(reduce()); // {width: 425, height: 150} | |
Implement
Array.prototype.reduce()
usingArray.prototype.forEach()
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
Array.prototype.reduce = function(callback, initialValue) { | |
let counter; | |
let accumulatedValue; | |
if (this.length === 0) { | |
return this; | |
} else { | |
if (arguments.length === 1) { | |
counter = 1; | |
accumulatedValue = this[0]; | |
} else if (arguments.length == 2) { | |
counter = 0; | |
accumulatedValue = initialValue; | |
} else { | |
throw 'Invalid number of arguments were passed.' | |
} | |
} | |
while (counter < this.length) { | |
accumulatedValue = callback(accumulatedValue, this[counter]); | |
counter++; | |
} | |
return [accumulatedValue]; | |
}; | |
console.log([1, 2, 3].reduce(function(p, c) { | |
return p + c; | |
})); // [6] | |
console.log([1, 2, 3, 4, 5].reduce(function(p, c) { | |
return p > c ? p : c; | |
})); // [5] | |
var boxarts = [ | |
{ width: 200, height:200 }, | |
{ width: 150, height:200 }, | |
{ width: 300, height:200 }, | |
{ width: 425, height:150 } | |
]; | |
console.log(boxarts.reduce(function(p, c) { | |
return p.width * p.height > c.width * c.height ? p : c; | |
})); // [{height: 150, width: 425}] | |