Sum All Numbers in a Range why won't this work?

Sum All Numbers in a Range why won't this work?
0

#1

Tell us what’s happening:
I’ve created a new variable, sum, initialized to 0. I sorted the array from low to high with the sort method. I ran a for loop and initialized i to the arr[1], and worked down to arr[0]. The loop does not seem to be adding i to the sum. I can’t figure out the reason for this. I would greatly appreciate if someone could give an explanation for this.

Your code so far

function sumAll(arr) {
  var sum = 0;
  
 
  arr.sort(function(a,b){
    return a-b;
  });
  
  for(var i = arr[1]; i < arr[0]; i--){
    
    sum += i;
    
  } return sum;
}

sumAll([4, 9]);

Your browser information:

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

Link to the challenge:


#2

Check the condition in the for-loop. It never evaluates to true, so it never runs.


#3

Why do you sorting array?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of


#4

Thanks @kevcomedia, Needed a > , not a < .


#5

@0Prime The problem requires you to solve arrays where the larger number comes before the smaller number. There’s probably a way you can solve the problem without sorting, but the way I set up my for loop required me to first sort the array from smallest to largest number.


#6

You can use Math.max() and Math.min() to get the smaller and larger numbers.


#7

@kevcomedia oh right, I see where you are going with that. Set i = Math.max(arr) and so on. Yeah, definitely a better way to solve the problem.


#8

@kevcomedia @0Prime thank you two for taking a look over my code. :handshake:


#9

It’s a good solution when you only need either max or min number. When you want both - it’s easer just sort them:

const [min, max] = pair.sort()
// instead of:
const min = Math.min(...pair)
const max = Math.max(...pair)

#10

…except JS treats array contents as strings by default when sorting, and I find writing the sort function callback cumbersome just to sort two numbers. I find the min and max more straightforward, but to each their own!