Please let me know what did I do wrong, the function is perfectly fine with in put [4,1], but doesnt work with arr = [10,5]
I think it is because of sort(), I didnt understand the all the error with sort()
please let me know if you can fix this.
Your code so far
function sumAll(arr) {
var newArr = arr.sort();
var total =0;
for(let i= newArr[0]; i <= newArr[1]; i++){
total += i;
}
return total;
}
console.log(sumAll([1, 4]));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.
I would suggest finding the largest and smallest of the two numbers and saving them to a variable. Then make a for loop that adds numbers between the variables to a result. Now, you can return the result.
Yes, I can use min, max, but I still want to know why sort() isnt work in this case. In theory I can sort the array and have a newArr start with min, end with max and just do the for loop on that newArr. But this isnt working practically and I really want to know why.
thanks, I am so happy, so fix this by not using default sort(), I add this, and then I pass the challenge.
function sumAll(arr) {
var newArr = arr.sort((a,b)=>a-b);
var total =0;
for(let i= newArr[0]; i <= newArr[1]; i++){
total += i;
}
return total;
}
You are correct. the problem you are experiencing is because the .sort() method. It’s quite complicated to describe, but basically, the sort() method is turning your array elements into strings and then comparing them in the UTF-16 code units order.
Low and behold this means that the number 10 comes before 5!