Skip to content Skip to sidebar Skip to footer

How Does Javascript Decide Sort Order With Characters From Different Character Sets?

I was working on some code where I need to perform an alphabetic ascending sort (standard .sort()) behavior and I wondered how sorting works with special characters and characters

Solution 1:

If you don't provide your own comparision function, then per the ECMAScript spec, here are the rules:

  1. If x and y are both undefined, return +0.
  2. If x is undefined, return 1.
  3. If y is undefined, return -1.
  4. If the argument comparefn was not provided in the call to sort, go to step 7.
  5. Call comparefn with arguments x and y.
  6. Return Result(5).
  7. Call ToString(x).
  8. Call ToString(y).
  9. If Result(7) < Result(8), return -1.
  10. If Result(7) > Result(8), return 1.
  11. Return +0.

For your particular case, it is determined by steps 7-11.

And, the < and > operators compare the Unicode encoding value of the first differing character.

For finer grain control over the situation, MDN recommends using your own custom compare function that uses String.localeCompare() which contains a bit smarter logic for sorting characters.

Post a Comment for "How Does Javascript Decide Sort Order With Characters From Different Character Sets?"