Sorting function

Tell us what’s happening:
Hi, im learning about sorting in JS. I wonder why we can’t use sort((a,b)=>a-b) instead of sort((a,b) => a === b ? 0: a<b? -1:1) for sorting characters like sorting numbers. Please explain it to me, thank you.

  **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/93.0.4577.63 Safari/537.36

Challenge: Sort an Array Alphabetically using the sort Method

Link to the challenge:

Hi,
I have been trying to earn sort() method and I encounter this one recently. I am quoting this part from MDN.

  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.

In the case of a string, we can only have these outputs for the sort method to kinda figure out where it should put the item.

  • If compareFunction(a, b) returns a value > than 0, sort b before a .
  • If compareFunction(a, b) returns a value < than 0, sort a before b .
  • If compareFunction(a, b) returns 0, a and b are considered equal.

But if the input is only numbers then you can have other values as well.

To compare numbers instead of strings, the compare function can subtract b from a . The following function will sort the array in ascending order (if it doesn’t contain Infinity and NaN ):

function compareNumbers(a, b) {
  return a - b;
}
1 Like

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