0

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thanks Yosvel, it works perfectly now. If you don't mind, could you explain what each of those elements in the regex do? I don't know much about them. Or do you know a source where I could look them up?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.