0

I want to sort this array by ascending

const data = ["10",  "11",  "12",  "13",  "14",  "3",  "35 ½",  "36",  "36 ⅔",  "37 ⅓",  "38",  "38 ⅔", "4", "40"]

I used this logic but not work

data.sort((a: string, b: string) => +(a > b) || -(a < b))

Expect result:

const data = ["3", "4", "10", "11", "12", "13", "14", "35 ½", "36", "37 ⅓", "38",  "38 ⅔", "40"]
  • 2
    Use `.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))` – CertainPerformance Nov 10 '22 at 05:15
  • @CertainPerformance Nice one. I didnt know the third property way. I used to use `+a - +b` But this will fail for 35 and a half scenario – Rajesh Nov 10 '22 at 05:17
  • @CertainPerformance it can't handle `½` and `⅓`. My guess is it cant parse the values to numbers, so it just sorts them lexicographically. `"½".charCodeAt(0) == 189` and `'⅓'.charCodeAt(0) == 8531` – adiga Nov 10 '22 at 05:30

0 Answers0