Functional Programming: Sort an Array Alphabetically

Tell us what’s happening:
Describe your issue in detail here.

After doing the code, mine seems to work but is different from FCC solution. I am a bit confuse with a > b and -1 : 1 solutions. Can someone explain in great depth about it?

  **Your code so far**
return arr.sort((a, b) => a === b ? 0 : a > b ? 1 : -1)
// this is what I did to pass

return arr.sort((a, b) => a === b ? 0 : a < b ? -1 : 1)
// this is what I found FCC solution
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36

Challenge: Sort an Array Alphabetically using the sort Method

Link to the challenge:

Do you understand how the ternary operator works?

In terms of if/else statements, yours is this:

if (a === b) {
  return 0;
} else if (a > b) {
  return 1;
} else {
  return -1;
}

theirs is this

if (a === b) {
  return 0;
} else if (a < b) {
  return -1;
} else {
  return 1;
}

The logic is the same, it’s the order of statements that are flipped around.

thanks for your kind advice for beginners. It makes sense now.

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