[TIL] sort() vs localCompare() in Javascript

sort()

The sort() method sorts the elements of an array into appropriate positions and returns the array.
The default sort order follows the Unicode point of the string.

arr.sort([compareFunction])

If compareFunction is not provided, it converts the elements to strings and compares the strings in Unicode point order.

If compareFunction is provided, array elements are sorted according to the return value of the compare function.

  • If compareFunction is (a, b) < 0, sorting will be done in this order => a , b

  • If compareFunction is (a, b) > 0, sorting will be done in this order => b, a

  • If compareFunction returns 0, it will maintain the order.

function customSort(a,b) {
    if(a < b) return -1; // a, b
    if(a > b) return 1; // b, a
    if(a == b) return 0; // maintains the order a, b or b, a
}
  • If you want to sort in an ascending order, then return a - b
  • If you want to sort in a descending order, then return b - a

localeCompare()

The localeCompare method returns a number indicating whether the referenced string comes before, after, or is equal to the given string in the sort order.

referenceStr.localeCompare(compareString[, locales[, options]])

Returns -1 if referenceStr is before compareString, 1 if it is behind compareString, and 0 if they are equal.

'a'.localeCompare('b') // -1 , 
'b'.localeCompare('a') // 1
'c'.localeCompare('c') // 0