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

191
Views
How to parse numbers in strings and sort them?

I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.

Example:

const array = ["test 3","test 1","some test","another test","test 2"];

Expected result: test 1, test 2 , test 3, another test, some test

Preference for es6 solution.

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

0

You need to get a numerical value from the string or a large value to sort strings without any digit to the bottom. then sort by string.

const
    getDigits = s => (s.match(/\d+/) || [Number.MAX_VALUE])[0],
    array = ["test 3", "test 1", "some test", "another test", "test 2"];

array.sort((a, b) =>
    getDigits(a) - getDigits(b) ||
    a.localeCompare(b)
);

console.log(array);

about 4 years ago · Juan Pablo Isaza Report

0

const array = ["test 3","test 1","some test","another test","test 2"];
array.sort(function(a, b) {
    let aNumber = a.replace( /^\D+/g, '');
    let bNumber = b.replace( /^\D+/g, '');
    if (aNumber.length * bNumber.length) {
        a = parseInt(aNumber);
        b = parseInt(bNumber);
    } else if (aNumber.length + bNumber.length) {
        return aNumber.length ? -1 : 1;
    }
    return ((a === b) ? 0 : ((a > b) ? 1 : -1));
})
console.log(array);

So, you have three main cases

  • 1: Both items contain numbers. In this case you need to extract the numbers from both and compare them
  • 2: Exactly 1 item contains numbers. In this case it will precede the other value
  • 3: None of the items contain numbers. In this case we compare the items as they are
about 4 years ago · Juan Pablo Isaza Report

0

You can use this function :

array.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));
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!