Monday, November 2, 2015

Bonfire:Sum of all Numbers in a Range.

I skipped directly to the Bonfires, since for Ziplines i think i need to brush up a little more on Bootstrap and HTML, CSS.
Planning to do the codeacademy tracks and become little more confident before i do the Ziplines.

This is my solution for sum of all numbers in a range.

Math.min() and Math.max() did not work when i passed the arr.
So googled it a bit and then passed elements of the array.

The sum of numbers in a range using Array.reduce() was already given in MDN example.
Solution:

function sumAll(arr) {
  var newarray = [];
  var minofarray = Math.min(arr[0],arr[1]);
  var maxofarray = Math.max(arr[0],arr[1]);
  for(i=minofarray;i<=maxofarray;i++){
    newarray.push(i);
    
  }
  var sumofarr = newarray.reduce(function(a, b) {
  return a + b;
});
  return sumofarr;
  
}

sumAll([1, 4]);

No comments:

Post a Comment