Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

46
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.

7 months 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);

7 months 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
7 months 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));
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs