Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Ordenar matriz alfanuméricamente y con una condición

Estoy tratando de reordenar una matriz por dos condiciones. Asegurándose de que Pos 10 va después de un solo dígito y que sigue un orden específico después de eso.

Traté de dar prioridad a la cadena que incluye first , pero luego, si quiero ordenar alfanuméricamente, restablece A en la parte superior. ¿Cómo podría obtener el resultado esperado?

 const arr = [ 'Pos 10 second', 'Pos 10 A third', 'Pos 10 first', 'Pos 1 second', 'Pos 1 A third', 'Pos 1 first', 'Pos 2 second', 'Pos 2 A third', 'Pos 2 first', ] const res = arr.sort((a, b) => { if (a.includes('first')) { return -1 } else { return 1 } }).sort((a, b) => a.localeCompare(b, 'en', { numeric: true})) console.log(res) /* Expected output [ 'Pos 1 first', 'Pos 1 second', 'Pos 1 A third', 'Pos 2 first', 'Pos 2 second', 'Pos 2 A third', 'Pos 10 first', 'Pos 10 second', 'Pos 10 A third' ] */

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Para la segunda ordenación, use la match de números dentro del valor de cadena, convertido a Number .

 const sorted = [ 'Pos 10 second', 'Pos 10 A third', 'Pos 10 first', 'Pos 1 second', 'Pos 1 A third', 'Pos 1 first', 'Pos 2 second', 'Pos 2 A third', 'Pos 2 first', ] .sort((a, b) => a.includes(`first`) ? -1 : 1) .sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/)); document.querySelector(`pre`).textContent = JSON.stringify(sorted, null, 2);
 <pre></pre>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!