Sum All Numbers in a Range Problem

Tell us what’s happening:

Your code so far

function sumAll(arr) {
  
  var sum = 0;
  
  for(var i=0; i<arr.length; i++){
    
   sum += Math.max(arr[i]) + Math.min(arr[i]);     
  }
  
  
  return sum;
}

sumAll([1, 4]);

Your browser information:

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

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


function sumAll(arr) {
  
  var sum = 0;
  var min = Math.min(arr);
  var max = Math.max(arr);
 
  
  
  for(var i = min; i <= max; i++){     
    sum += i;
  }
  
  
  return sum;
}

sumAll([1, 4]);

this should work but it doesn’t

Math.min and Math.max accept arguments which need to be numbers. arr is an array, so since an array is not a number, each of the functions returns the value NaN. This causes the for loop to not execute the code inside, so sum remains 0.

I will give you two hints on how you can get the correct values of min and max.

  1. One way would be to check if the first element of arr is greater than the second element of arr. If it is, assign max the value of the first element and min the value of the second element. Otherwise, the max should be assigned the value of the second element and min the value of the first element.

  2. Another way is to look into how you could use the apply function with the Math.max and Math.mix functions to allow you to use arr’s elements as arguments/values for the functions.

1 Like

Thank you that works.


function sumAll(arr) {
  
  var sum = 0;
  var min;
  var max;
 
  
  if(arr[0] < arr[1]){    
      min = arr[0];
      max = arr[1];
    }else{
      min = arr[1];
      max = arr[0];
    }
  
  for(var i = min; i <= max; i++){     
    
    sum += i;
  }
  
  
  return sum;
}

sumAll([1, 4]);

yeah that’s great :slight_smile:

How would you implement the above function so it accepts two arguments, rather then one? @camperextraordinaire

Hi, why is this code not running.
function sumAll(arr) {

var max = Math.max(arr);

var min = Math.min(arr);

var sum=0;

for(var i =min ; i<=max; i++ ) {

sum += i;

}

return sum;

}

you will need to tell also what is failing. What error do you get. What are the requirements?

In the future, please create your own topic when you have specific questions about your own challenge code. Only respond to another thread when you want to provide help to the original poster of the other thread or have follow up questions concerning other replies given to the original poster.

The easiest way to create a topic for help with your own solution is to click the Ask for Help button located on each challenge. This will automatically import your code in a readable format and pull in the challenge url while still allowing you to ask any question about the challenge or your code.

Thank you.