Return b.length - a.length;

This example shows the effect of different comparison callbacks on sorting a bunch of numeric strings


function sortstrings() {
const strings=["1", "2", "3", "10", "11", "20", "21", "31", "0100", "01", "02", "03", "010", "001"]

// sort copies of strings array
// default sort order is by increasing Unicode code point values
const strings_default_sort=[...strings].sort()
// sort as strings
const strings_by_dictionary_order=[...strings].sort(lexico_order)
// sort as numbers
const strings_by_numeric_value=[...strings].sort(numeric_order)
// sort by string length
const strings_by_length=[...strings].sort(length_order)

console.log(`strings ${JSON.stringify(strings)}`)
console.log(`default sort ${JSON.stringify(strings_default_sort)}`)
console.log(`lexicographic order ${JSON.stringify(strings_by_dictionary_order)}`)
console.log(`numeric order ${JSON.stringify(strings_by_numeric_value)}`)
console.log(`length order ${JSON.stringify(strings_by_length)}`)
}

sortstrings()

Here are the different compare callbacks

function numeric_order(a, b) {
  return parseInt(a, 10) - parseInt(b, 10)
}

function lexico_order(a, b) {
  //return a.localeCompare(b)
  return a < b? -1: a > b? 1: 0
}

function length_order(a, b) {
  return a.length - b.length
}

This is the output

strings ["1","2","3","10","11","20","21","31","0100","01","02","03","010","001"]
default sort ["001","01","010","0100","02","03","1","10","11","2","20","21","3","31"]
lexicographic order ["001","01","010","0100","02","03","1","10","11","2","20","21","3","31"]
numeric order ["1","001","01","2","02","3","03","10","010","11","20","21","31","0100"]
length order ["1","3","2","10","11","20","21","31","03","01","02","010","001","0100"]

1 Like