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.
@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.
…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!