Reputation: 113
I'd like to sort an array of Strings which include both Usernames & Points in the same string from Highest to Lowest, without losing the usernames, how do I do this?
I've tried:
arrayName.sort()
However, I have no idea how to make it work with strings! >w<
Here's what I'm working with:
let uwu = [
"hinata:5000",
"hiro:3000",
"karuki:6000",
"arisu: 4000"
]
Now I'd like to sort it into a new array, from Highest Points to lowest, like below! >w<
Expected Output:
["karuki:6000", "hinata:5000", "arisu:4000", "hiro:3000"]
Please do help me ! Thank you in advance !
Upvotes: 0
Views: 60
Reputation: 370929
Have a helper function that extracts the digits from the string, then call that function on both elements in the sort callback and return the difference:
const input = [
"hinata:5000",
"hiro:3000",
"karuki:6000",
"arisu: 4000"
];
const getNums = str => str.match(/\d+/)[0];
input.sort((a, b) => getNums(b) - getNums(a));
console.log(input);
Upvotes: 2