Sort an Array Alphabetically using the sort Method

Tell us what’s happening:
Could someone explain to me why this passed the challenge.
I referenced the examples given and I’m curious as to why the way they wrote it out didnt work for me and this way did.

Your code so far


function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort();
    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.87 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

Sort by default will sort based on character code (A, B, C,… then a, b, c…, etc). So you return the sorted array. The return a-b doesn’t do anything, because you’ve already returned and exited the function at the point

Edit just to expand on that, so there are two things here:

Firstly your function looks like this:

function alphabeticalOrder(arr) {
  return arr.sort....
  // Nothing after that return line does anything
  // JS doesn't need to look at it because the
  // function has already exited:
  return ....
}

And secondly, sort, if you don’t tell it how you want to sort, sorts things in this order (unicode points - this is just Latin alphabet bit of unicode, but it’s the one that applies here):

https://www.key-shortcut.com/en/writing-systems/abc-latin-alphabet/

So if you have a list of words like dog cat rabbit horse it will sort them cat dog horse rabbit. If you add Zebra (note uppercase), you’ll get Zebra, cat dog, horse, rabbit because uppercase Z comes before lowercase a. And if you have numbers, like 2, 3, 10, 1, sort will sort them 1, 10, 2, 3 (1 comes before 2, it doesn’t treat them as numbers)

4 Likes

for alphabetical order, you can use it. it works for me.

function alphabeticalOrder(arr) {
  // Add your code below this line
  const sortArr = arr.sort((a, b) => {
    return a > b;
  });

  console.log(sortArr);

  return sortArr;
  
  // Add your code above this line
}

It cannot work neither for you or for anyone as it’s very incorrect. I suggest you check what .sort() does by its own, without any arguments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

This is my solution but it didnt work, still wondering why?

var sorted = arr.sort(function(a, b){
  return a > b
})
return sorted
2 Likes

Solution passes for me, but technically it isn’t quite correct, so I think it will fail on some platforms. Someone in another thread was finding it failed on Chrome, it just didn’t sort at all. It works on Firefox and Chromium for me. I think Chrome changed how it implemented sort quite recently (in September afaik, from Chrome 70 onwards) so it might be due to that. Try clearing cache and resubmitting first though. Two things:

  1. The function you give to sort should return -1 (or any negative number), 0 or 1 (or any positive number), yours returns true or false. This doesn’t matter on some platforms, but the -1, 0, 1 is necessary for a consistent sort. Which leads to:
  2. What does > mean here? For example, what does "Hello" is greater than "Goodbye" mean?

This isn’t your fault at all - the description here uses <, and that seems to have worked everywhere up until quite recently.

EDIT: Note JavaScript provides a method for strings specifically for doing this. Example:

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

And to reverse the order, just switch the a and the b:

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

This is kinda important, but a little bit more advanced than the level the challenge is at: the challenge assumes a basic, lowercase English alphabet (a-z). But firstly, what happens if it includes uppercase characters? Secondly, what happens if the alphabet is not a-z - should ä be qual to a or not, if not does it come before or after b, etc etc.

9 Likes

function alphabeticalOrder(arr) {
// Add your code below this line
var newArr = arr.sort();
console.log(newArr);
// Add your code above this line
return newArr;
}
alphabeticalOrder([“a”, “d”, “c”, “a”, “z”, “g”]);

Thank you for this, had been scratching my head.

I was even checking with conditions for a===b, thinking that might be the reason why the test is not passing

Fastes solution:

function alphabeticalOrder(arr) {
return arr.sort();
}

It’s the correct solution for sorting letters in alphabetical order,

But if you want to sort numbers

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

1 Like

It doesn’t sort in alphabetical order, it sorts in order of string codepoints (if it was alphabetical, then A a B b C c would stay in that order, but that is not the case).

1 Like

You right,

arrayList.sort((a, b) => {
return a > b;
})

Thanks for this. I couldn’t figure out why my code wasn’t passing the challenge. It worked in a Javascript Jupyter Notebook running in Chrome, but not in the Chrome console. I tried the Firefox console and that worked. I wonder what the reason is. I have Chrome 71, btw.

I ended up using Firefox to complete it. Thanks again for troubleshooting!

Chrome 70 and Node.js 11 no longer sort arrays properly using functions returning Boolean !
You comparison should return 0,1,-1.

function alphabeticalOrder(arr) {
  return arr.sort((a, b) => {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
  });
3 Likes

Thank you!!! I used the String.localeCompare and it worked! I was starting to become frustrated before that.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

1 Like

I feel that the lesson in this section does not really teach you to solve the challenge. This should be looked into by freeCodeCamp.

The answer to this challenge is simply:

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

I looked at the MDN documentation for the sort() method. By default, sort() will sort an array of letters or numbers, alpabetically or in ascending order, respectively. See MDN description of sort() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

3 Likes

The hint was correct for all browsers up until autumn last year when Chrome changed its sort algorithm. This has been picked up many times in the forums, and there is an amendment, it’s just not live yet.

Edit: note that the sort function neither sorts alphabetically nor in an expected ascending order, for example:

["Animal", "vegetable"].sort() // returns ["Animal", "vegetable"]
[10, 9].sort() // returns [10, 9]

thank you so much!!!

This is exactly my same solution to the challenge.
Using the .sort((a, b) => a > b) as in the page’s example won’t work (chrome 74).

Just use : return arr.sort();