Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda