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.