how to sort strings based on a substring JS

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.

Answer

You can create a function to extract the last number id using a RegExp combined with String.prototype.match():

Regular expression: /d+(?=D*$)/

  • d matches a digit (equivalent to [0-9])
  • + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • Positive Lookahead (?=D*$) Assert that the Regex below matches D matches any character that’s not a digit (equivalent to [^0-9])
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • $ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

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)