0

I'm trying to sort the list provided below, yes it's full of strange values, but it's the data I have to work with.

The expected result is:

["3 $", "4 $", "4a $", "5-5b $$", "6 $", "10 $", "10 b $", "11 $"]

But instead I get:

["10 $", "10 b $", "11 $", "3 $", "4 $", "4a $", "5-5b $$", "6 $"]

This happens because "10" < "3" is true.

But I'm at a loss as to how I would go about comparing these values without converting them to numbers, in which case another issue will arise, namely the sorting of values such as "4 $", "4a $", "4b $", "4c $".

let list = ["5-5b $$", "4 $", "10 $", "10 b $", "4a $", "6 $", "3 $", "11 $"];

Here is my code so far:

console.log(list.sort(function(a, b) {
 let x = a.replace(/\-/, ".").replace(/\$+/, "").replace(/\s/g, "");
 let y = b.replace(/\-/, ".").replace(/\$+/, "").replace(/\s/g, "");
 
 console.log(`Comparing ${x} to ${y}`)
 
 return x.localeCompare(y);
}))

All input is appreciated.

Run_Script
  • 2,487
  • 2
  • 15
  • 30
MMStarr
  • 151
  • 1
  • 5
  • 1
    First you need to decide how you would order them. Are you trying to sort by the first number in the string? How do you handle `5-5b`? Does `4 a` come before `4b` (aka do spaces matter) etc etc. – DBS Jul 15 '20 at 12:13
  • 2
    just take the second answer with `localeCompare` and options. – Nina Scholz Jul 15 '20 at 12:15
  • I think splitting the elements of the list (on the basis of whitespace as well as "-"), and then sorting on the basis of first element might do the trick. – dev404 Jul 15 '20 at 12:32

0 Answers0