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

203
Views
Javascript sort mixed alphanumeric array - letters ascending, numbers descending

I have an alphanumeric array that I need to sort by alphabet ascending and then by number descending, the array is a as follows:

[A1, A4, A2, A3, C2, C4, C3, B3, B5, B4]

How do I sort the array using JavaScript, so it looks like:

[A4, A3, A2, A1, B5, B4, B3, C4, C3, C2]

I have tried:

arr.sort() 

but that only sorts it alphabetically and numerically ascending, giving me:

[A1, A2, A3, A4, B3, B4, B5, C2, C3, C4]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you have always a single letter, you could sort by the numerical rest and by the first letter.

const
    array = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];

array.sort((a, b) => a[0].localeCompare(b[0]) || b.slice(1) - a.slice(1));

console.log(...array);

If you have more than one letter, you could take a regular expression and get only digits and non digits, separated into an object.

const
    getValues = string => ({
        letters: string.match(/\D+/)[0],
        digits: string.match(/\d+/)[0]
    }),
    array = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];

array.sort((a, b) => {
    const [aa, bb] = [a, b].map(getValues);

    return aa.letters.localeCompare(bb.letters)
        || bb.digits - aa.digits;
});

console.log(...array);

about 4 years ago · Juan Pablo Isaza Report

0

array.sort take a callback where you can define the condition on how you compare two elements in your array

to perform your need an idea can be to return the comparison of second character if first one is identical

var data = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];
var result = data.sort((a, b) => {
  if (a === b) {
     return 0;
  }
  if (a[0] === b[0]) {
    return (a[1] > b[1]) ? -1 : 1;
  }
  return (a > b) ? 1 : -1;
});
console.log(result);

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!