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

181
Views
How to sort an alphanumeric array just based on number in javascript?

consider the following array:

['state1035', 'dm5', 'state123', 'county247', 'county2']

sorting this array on basis of number output should be:

['county2' ,'dm5', 'state123', 'county247', 'state1035']
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Assuming the strings will have numbers together and at the end you can use match to extract the number and sort it:

let arr = ['state1035', 'dm5', 'state123', 'county247', 'county2'];
console.log(arr.sort((a,b) => a.match(/\d+$/).pop() - b.match(/\d+$/).pop()));

The match method used within the compare function will return the array of matched sub-strings from the given string. The regex \d+ will match with numbers at the end and we are sorting based on these numbers.

about 4 years ago · Juan Pablo Isaza Report

0

Use a regular expression to match against only the numbers in the string, and then sort the strings based on those numbers.

const data = ['state1035', 'dm5', 'bob0Bob', 'state123', 'county247', 'county2'];

const regex = /\d+/;

const result = data.sort((a, b) => {
  return a.match(regex) - b.match(regex);
});

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!