 # Sort an Array Alphabetically using the sort Method(Sorting)

Sort an Array Alphabetically using the sort Method(Sorting)
0

#1

Hi All,

I was trying to sort an array of letters alphabetically and my function does not pass any of the tests.
Any help would be appreciated.

Your code so far

``````
function alphabeticalOrder(arr){
// Add your code below this line
return arr.sort(function(a, b){
return a - b;
});

// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
``````

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

#2

try adding logs so you can understand why it doesn’t pass.
For eg. log the value of a-b before you return it. Does it give you what you thought it would?

(CTRL-SHIFT-J will show you the developer tools and console on Chrome browser so you can track your console.log statement outputs)

#4

[spoiler]

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

;[/spoiler]

#5
``````function alphabeticalOrder(arr) {
// Add your code below this line
return arr.sort(function(a, b){
return a > b;
})
// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
``````

#6
``````function alphabeticalOrder(arr) {
// Add your code below this line
return arr.sort();

// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
``````

This passed the level. Try this #7
``````return a >b
``````

These kinds are called Compare Functions used to Sort the arrays.
If this function not used, the array is sorted according to each character’s Unicode code point value, according to the string conversion of each element.

#8

Thank you. Was stuck

#9

a>b shall return true or false, while the sort function require the return type is a number.
You can try this: return a > b ? 1 : -1

#10

a and b are character so a-b return NaN (Not a Number). You can check by: console.log(a-b);
Sort function require the return type is a number. You can try this: return a>b ? 1:-1.

#11

@manh-trinhquoc thank you for your answer. I was stuck on this and the posted solution is incorrect as it simply uses `a > b` and does not “convert” it to a number.