Sort an Array Alphabetically using the sort Method(Sorting)

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"]);

Your browser information:

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.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method

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)

[spoiler]

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

;[/spoiler]

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"]);

Please help me why my code is not working

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 :wink:

5 Likes
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.

Thank you. Was stuck

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

1 Like

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.

2 Likes

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