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

195
Views
How to sort an array by numbers in strings?

I have an array:

[
  'B3', 'B4', 'B5',
 
  'B6', 'C3', 'C4',
 
  'C5', 'C6', 'D3',
 
  'D4', 'D5', 'D6'
]

I need to sort it by the number in each string (in ascending order). The number can be one/double-digit/triple-digit.

Here's what the final array should look like:

[
  'B3', 'C3', 'D3',
 
  'B4', 'C4', 'D4',
 
  'B5', 'C5', 'D5',
 
  'B6', 'C6', 'D6'
]

How can I do it?

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

0

Assuming that there will always be only one letter at the beginning - then here is the solution:

const input = [
    'B3', 'B4', 'B5',
    'B6', 'C3', 'C4',
    'C5', 'C645', 'D3',
    'D4', 'D532', 'D6'
];

console.log(sort(input));

function sort(array) {
   return array.sort((a, b) => {
       const aVal = parseInt(a.slice(1), 10);
       const bVal = parseInt(b.slice(1), 10);

       if (aVal < bVal) {
           return -1;
       }
       if (aVal > bVal) {
           return 1;
       }

       return 0;
   });
}

about 4 years ago · Juan Pablo Isaza Report

0

You can have a look to the sort method: https://www.w3schools.com/jsref/jsref_sort.asp

And how you can pass a function in for values comparison as a criteria to sort the elements :)

const myArray = [
  'B3', 'B4', 'B5',
 
  'B6', 'C3', 'C4',
 
  'C5', 'C6', 'D3',
 
  'D4', 'D5', 'D6'
]

const sortedArray = myArray.sort((a, b) => a[1] - b[1])
console.log(sortedArray)

about 4 years ago · Juan Pablo Isaza Report

0

You can use sort method of array with custom comparator function as:

const arr = [
  'B3', 'B4', 'B5',
  'B6', 'C3', 'C4',
  'C5', 'C6', 'D3',
  'D4', 'D5', 'D6',
];

const result = arr.sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!