看看别人写的字符串排序!#JS_codewar_2

题目

Your task is to sort a given string. Each word in the String will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.
For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"

我的

function order(words){
    var alpha = words.split(' '); //['this1', '2to', ...]
    var box = [];
    try 
    {
        alpha.map(function(abc){
            var sq = abc.replace(/[^\d]/g, '');
            box.push([sq, abc]);
        });//[[1, 'this1'], [2, '2to'], ...]
    
        box.sort(function(a, b){return a[0] - b[0]});

        let sentence = box.reduce(function(acc, cur){return acc + ' ' + cur[1]}, '');
        return sentence.replace(/(^\s*)/g, '');
    }
    
    catch(err){
        return ''
    }        
}

别人的

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

想法

想哭,看看别人的,多么简洁。

推荐阅读更多精彩内容