# Sort() method error problem!

Tell us what’s happening:

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.

``````
function sumAll(arr) {
var newArr = arr.sort();
var total =0;
for(let i= newArr[0]; i <= newArr[1]; i++){
total += i;
}
}

console.log(sumAll([1, 4]));

``````

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`.

Challenge: Sum All Numbers in a Range

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.

Sort doesn’t do exactly what you would think:

You can set the function used to sort the array:
https://www.w3schools.com/jsref/jsref_sort.asp

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.

This part is why `sort` doesn’t do what you expect.

1 Like

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;
}
}

console.log(sumAll([10, 5]));

1 Like

That’s exactly the fix that worked for me too. Nice work!

1 Like

I am not gonna use default sort() anymore, lesson learned

1 Like

hey there

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!

i.e. “10” is less than “5”

No! I hear you scream

There’s some reading here: .sort() method problem

But the solution is fairly simple:

You just need to provide a compare function for the `sort()` method.

i.e.

``````arr.sort(function compareMyArr (a, b) {
return a - b
}
``````

this will sort your array in ascending order

Hope this helps.
LT

1 Like