Sort an Array Alphabetically using the sort Method "Problem"

I tried this on Visual Studio Code, and it worked, why FCC doesn’t accept my code ? Is something wrong ?

Your code so far


function alphabeticalOrder(arr) {
  // Add your code below this line
    return arr.sort((a,b) => b-a);
  
  // 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/73.0.3683.103 Safari/537.36.

can’t use links yet kk

So, have you started using the console yet? It’s a great debugging tool, and here’s your code with a useful log output:

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

If you haven’t learned to use the console yet, read about it here.

In short, what’s happening is you’re trying to sort by subtracting a string from a string. Do you think that will get you where you want to be? What happens when you ADD a string to a string? If you add “a” to “b”, do you get “c”?

let myNewString = "a"+"b"; // what does this return?

So doing

let myNewString = "a"-"b"; 

will not return a numeric value at all. In fact, it will return NaN (not a number). You need to use a different comparator for strings.

1 Like

You might find useful the default behavior of sort when it is not given a compare function at all. See the “Description” section in the MDN docs:

2 Likes

The default is, by and large, great. Except that ‘a’ and ‘A’ are viewed as different entities with the default. Won’t matter in this particular instance, but generally speaking, I find the default behavior is deceptive. I will almost always provide SOME function to sort by.

Personally, I might suggest the same page, but a little further down, where it gets to sorting non-ascii characters. This will treat upper- and lower-case as the same.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Sorting_non-ASCII_characters

1 Like

I thought it best to not confuse the issue with locale-dependent collations. The challenge comes pretty early on IIRC, so the default behavior of sort is really what the challenge is looking for. I’m not sure the challenge is supporting best practices, but that could be said for half the challenges on FCC.

1 Like

very true, and good point.

This callback does not return a boolean, it just happens to be trying to subtract strings, which returns NaN.

1 Like