Reputation: 95
I have strings like these in an Array:
let arr = ["UserA | 3", "UserB | 0", "UserC | 2", "UserD | 1"]
Names and their ID's at the end. I'd like to sort it based on their id's at the end, but couldn't come up with a way to do it.
Upvotes: 0
Views: 813
Reputation: 19070
You can create a function to extract the last number id using a RegExp combined with String.prototype.match():
Regular expression: /\d+(?=\D*$)/
And finally use Array.prototype.sort()
Code:
const arr = ["UserE | 2020", "UserA | 3", "UserB | 0", "UserC | 2", "UserD | 1"]
const getId = s => +s.match(/\d+(?=\D*$)/)[0]
arr.sort((a, b) => getId(a) - getId(b))
console.log(arr)
Upvotes: 1
Reputation: 4419
You can do this using String#split
and Array#sort
, defining a custom compareFunction
function in this scheme:
MDN Web Docs:
- If
compareFunction(a, b)
returns a value > than 0, sort b before a.- If
compareFunction(a, b)
returns a value < than 0, sort a before b.- If
compareFunction(a, b)
returns 0, a and b are considered equal.
Like this:
let arr = ["UserA | 3", "UserB | 0", "UserC | 2", "UserD | 1", "UserE | 2020"];
arr.sort((a, b) => a.split(" | ")[1] - b.split(" | ")[1]);
console.log(arr);
Upvotes: 3