This challenge will have us code a function that takes in an array of two numbers. The function should return the sum of these two and every integer that lies in between. Note that, the order in which the input array is given will be random.
Here’s a few examples of what we should end up with:
sumAll([1, 5]); //-> 1+2+3+4+5 = 15 sumAll([11, 8]); //-> 8+9+10+11 = 38 sumAll([3, 1]); //-> 1+2+3 = 6
This task will become much easier if we find a way to reliably identify the largest and smallest number in the array. Then, a for loop should help us sum up every number in between. Let’s get working:
function sumAll(arr) { var max, min, sum = 0; // Find max and min values in the array, and asign them to their respective variable. for (var i = min; i <= max; i++) { sum += i; } return sum; }
Seems straightforward, we first identify the minimum and maximum values, and then loop from min up to max, incrementing by one (1) at every loop and adding it to out total sum. We now need to identify the min and max values.
For this task, we are going to be using the Array.prototype.reduce() method. Reduce will iterate over and array and return a single value. For more information on functional programming and the reduce method, visit this site, it’s a great resource.
Here’s what we end up with:
function sumAll(arr) { var max = arr.reduce(function(a, b) { return Math.max(a, b); }); var min = arr.reduce(function(a, b) { return Math.min(a, b); }); var sum = 0; for (var i = min; i <= max; i++) { sum += i; } return sum; }
The reduce method takes a function which operates over every value inside the given array. The code we have written will work for arrays of any length, and will always return the largest or smallest number in that array.
This last version of the sumAll function should work everytime. Try visiting the resource I provided on functional programming. These tools are incredibly powerful and will be of great help in the future.