# Sort an Array Alphabetically using the sort Method - code not passing

This is my code so far. It doesn’t pass the tests. I don’t understand why

``````
function alphabeticalOrder(arr) {
return arr.sort(function(a, b) {
return a > b
})

}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36`.

SOLVED.

arr.sort() passes the test.

I don’t know why though. Perhaps someone can explain.
Highly appreciated

Strange…I tried your code just to be sure, and it does pass…

To answer your question why arr.sort() works… in the challenge note it states “JavaScript’s default sorting method is by string Unicode point value, which may return unexpected results.”

It works fine for alpha characters, if they are either all upper case or all lower case. Numbers are a mess, because their numerical order is not the same as their order by unicode point value

So for that reason, `[34,5,67,13,2, 71].sort();`
returns `[ 13, 2, 34, 5, 67, 71 ]`

but if you write your own sort function as in the challenge, it returns `[ 2, 5, 13, 34, 67, 71 ]` as expected. So pretty much, it’s good to know when to use the built in sort method, and when (and how) to write your own to avoid any surprises.

2 Likes

It may be a browser issue. Please see my post at The sort method behaves different on different browsers

2 Likes

I had the same issue. Seems to be a Chrome issue. Using the examples given in the challenge will not work in the Chrome console, but will in the Firefox console. Same with your initial solution that wasn’t working.

the sort function require the return type is a number to work correctly (<0, >0). 0 will leave a,b unchanged.

a>b will return true or false. True may be interpreted as a number (!=0) and false may be interpreted as 0. Which is not match the requirement of the sort function.

I don’t know what happen in FF but Chrome follow the rule.