2

//This is a function to sort a string according to integers

function order(words) {
    var str = words.split(' ');
    var newArr = [];
    console.log(str);
    console.log('----');
    for (var i = 0; i < str.length; i++) {
        var sorted = str[i].split('').sort();
        newArr.push(sorted);
    }
    console.log(newArr);
    var newar = [];
    for (var j = 0; j < newArr.length; j++) {
        newar += newArr[j].join('') + ' ';
    }
    console.log(newar.trim().split(' ').sort().join(' '));
}
order("is2 Thi1s T4est 3a");

//Result should be: Thi1s is2 3a T4est

2
  • What if a word contains more than one number or no numbers at all? Commented Oct 30, 2017 at 16:03
  • So in the sort add a method to find the numbers.... Commented Oct 30, 2017 at 16:05

2 Answers 2

6

Assuming, only one number is in a splitted string, then you could match a number and take it for sorting.

function order(string) {
    function getNumber(s) { return +s.match(/\d+/)[0] || 0; }

    return string
        .split(' ')
        .sort(function (a, b) { return getNumber(a) - getNumber(b); })
        .join(' ');
}

console.log(order("is2 Thi1s T4est 3a"));

Sign up to request clarification or add additional context in comments.

Comments

2

In one line:

function order(words) {
    return words
        .split(' ')
        .sort((a, b) => a.match(/\d+/) - b.match(/\d+/))
        .join(' ');
}  

1 Comment

This regex, will only match number from 0 to 9. Add \d+ regex to get all decimal value from 0 to 99999999...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.