Home > Software design >  how to sort strings based on a substring JS
how to sort strings based on a substring JS

Time:09-16

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.

CodePudding user response:

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);

CodePudding user response:

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)

  • Related