Sort method lesson question

my question is , how does the computer compare letters? does it compare them in binary, for example here ( a - d ), so computer turns in binary, and then check whether its a negative, possible number etc?

  **Your code so far**

function alphabeticalOrder(arr) {
// Only change code below this line

return arr.sort((a,b) => a === b ? 0 : a < b ? -1 : 1);
// Only change 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/98.0.4758.102 Safari/537.36

Challenge: Sort an Array Alphabetically using the sort Method

Link to the challenge:

Not binary, but generally yes - the computer turns letters into numbers for comparison. Or more specific: a computer saves any kind of character as a an integer-number according to an encoding-table. The most known is the ASCII table. This is also used to determine “alphabetical” order according to their integer value in the table.

However that doesn’t mean you can deal with characters as you would with numbers. The arr.sort() method will deal with it under the hood. In plain JavaScript you cannot subtract characters from eachother, while adding them will actually just combine the characters.

1 Like

This is a cool question. There’s a long answer, but I think the short answer is ASCII character codes…

ty you for your answers.

I have another question

this is an ascending order sort, if I change a < b ? 1 it will be a descending but there is an extra line in the code which is : -1 so shouldn’t it be an ascending order anyway because the last piece of code will reverse it?

The condition ? resultIfTrue : resultIfFalse is a ternary. You can flip the result by switching the result parts or negating the condition.

so if it false it doesn’t sort then, just to clear a confusion in my head.

(that is a question)

I’m not sure what you mean by “doesn’t sort”. The return value of the callback function determines where element a goes in relation to element b. Determining the order is how the method knows how to order the elements.

a < b ? -1 : 1); the original code
if a < b is true it returns -1 if false it returns 1 which means if a > b, so does it resort it according to the false value as well ?

Yeah, if a > b, then the callback returns 1.

Yeah okay I got it, I forgot that once a condition met it is met and it jumps to the other number to check the conditions. I don’t know for some reason why I thought, after the condition is met , it’s going to check another condition for same number lol.

p.s. maybe because I’m studying at 2 am xD

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.