Why is Sum All Numbers in a Range Function Broken?

I’m trying to create a new array consisting of each number ranging from 0 to the maximum number within given arguments; and then log the sum of the numbers from the new array. Any pointers? Can’t figure out what’s wrong with my code.

Your code so far

function sumAll(arr) {
  var newArr = [];
  var maxAmt = Math.max(arr);
  var reduceFunk = function getSum(a, b){
    return a + b;
  };
  
  for(var i = 0; i <= maxAmt; i++){
   
    newArr.push(i);   
      
  }
      return newArr.reduce(reduceFunk, 0);
  }

  
 

sumAll([1, 4]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/sum-all-numbers-in-a-range

Well, add a bunch of console.logs to see why you get 0. Since summing is hard to get wrong, it likely means you’re not generating the array properly, so it tries to sum an empty one. But why would that happen? :wink:

1 Like

So put the console.logs after each line of code? I guess, I’ll experiment. Thanks a lot! :money_mouth_face:

Ok, nice, a new one. Now I am wondering if i should be arr[i]? Thanks for the help.

no need using a for loop

function sumAll(arr) {
  let [a,b] = arr.sort((a,b) => a - b);
  return ((b - a) / 2 + a ) * (b - a + 1) 
}