Why b-a doesn't work with letters

Tell us what’s happening:

  **Your code so far**

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

// Only change code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));


  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36.

Challenge: Sort an Array Alphabetically using the sort Method

Link to the challenge:

Hello there.

Do you have a question?

If so, please edit your post to include it in the Tell us what’s happening section.

The more information you give us, the more likely we are to be able to help.

1 Like

Hi @castillorg !

It is always best to place your questions in the body of the topic.
You’ll get more responses that way.

This code right here should just be used for numbers

The reason being is that Javascript is a little funny when it comes to sorting numbers.

Let’s take this example array.
let arr = [3,100,24]

All the numbers are randomly sorted.
If I wanted to use the sort method for ascending order it would give me a funny result.

arr.sort()
//[ 100, 24, 3 ]

That obviously is not correct.
Javascript is looking at the first digit of each number. It only sees that 1 is less than 2. Not 100 and 24.

That is why you have to use this call back function.

 arr.sort((a, b) =>  a - b) 

The result would be this [ 3, 24, 100 ]

For this challenge, you can just use the sort method without a callback and it will pass.

You can also look at the FCC example and change it to fit the needs of the challenge to pass.

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? 1 : -1;
  });
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);

Hope that makes sense!

sorry @JeremyLT , I am just learning how this forum works, thank you for the advice

Thank you @jwilkins.oboe it gives me lots of new info and makes a lot of sense, however, I wanted to know why the a-b or b-a does not work when the array contains letters?

Subtraction is not defined for strings. Try running

console.log("a" - "b");
1 Like

The way humans read letters is very different from how computers read letters.

Computers don’t read a,b,c, like we do.
There are codes attached to those letters.

The sort method converts the elements to a string and then compares the UTF-16 code values.

It is a little confusing at first but the sorting method is a helpful tool to know.

I will also attach MDN docs which goes into more detail about compare functions, and different sorting examples.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

You could also look into this article on how sorting works with javascript

that is neat, thanks a lot @jwilkins.oboe

That is very helpful, thanks a lot

1 Like