I don’t know if it’s possible. I’ve tried looking everywhere for an answer, but nothing.
const points = ["Apple - 40", "Orange - 80", "Lemon - 140"];
points.sort(function(a, b){return b-a});
I tried doing this, however it didn’t do anything.
I don’t know if it’s possible. I’ve tried looking everywhere for an answer, but nothing.
const points = ["Apple - 40", "Orange - 80", "Lemon - 140"];
points.sort(function(a, b){return b-a});
I tried doing this, however it didn’t do anything.
3
Answers
Your current
sort()
logic is attempting to coerce the strings to numeric values. As they begin with alphabetic characters, that’s not going to work as you expect.To do what you require you need to manually extract the digits and sort those directly. There’s a lot of ways to do this. In the example below I used a regex to remove anything that’s not a digit, but other approaches may work better for the format of string available in your specific use case.
You can write a custom function for comparison like following
It gets the number from the string and compares them instead of comparing the whole string.
For the best performance just use
String#lastIndexOf()
to find the last space and slice the number: