【问题标题】:Ordering strings in an array according to number in string根据字符串中的数字对数组中的字符串进行排序
【发布时间】:2016-11-07 16:11:21
【问题描述】:

我正在尝试根据字符串中存在的数字对数组中的字符串进行排序,即。 'h2ello f3ere b1ow' 应返回 ['b1ow', 'h2ello' ,'f3ere'] 的数组。以下代码适用于两个元素(h2ello 和 b1ow),但在我添加第三个元素时无效。有谁知道这是为什么?

function order(words){
  var sentence = [];
  words = words.split(" ");
 for (var i=0;i<words.length;i++){
   for (var m=0;m<words[i].length;m++){
    if (!isNaN(parseFloat(words[i][m])) && isFinite(words[i][m])){
     var idx = words[i][m];
         sentence.splice(idx, 0, words[i]);
     }
   }
 }
 console.log(sentence);
}

order('h2ello f3ere b1ow');

【问题讨论】:

    标签: javascript string sorting integer


    【解决方案1】:

    最简单的方法是对数组进行直接排序,无需拼接到其他地方未知的地方(在循环中)。

    这个提议使用Array#sort 和一个回调来寻找一些小数来排序。

    var array = 'h2ello f3ere b1ow'.split(' ');
    
    array.sort(function (a, b) {
        return a.match(/\d+/) - b.match(/\d+/);
    });
    
    console.log(array);

    【讨论】:

      【解决方案2】:

      如果您查看有关 splice:Array splice 的文档,您将看到如果索引长于数组的长度,它将被设置为数组的长度。所以它只是做一个推送而不是设置你想要的索引。一种解决方案是手动设置:

      sentence[idx-1] = words[i]
      

      根据您的需要,您还可以稍微简化您的功能:

      function order(words){
        words = words.split(" ").sort(function(a,b){
          return a.match(/\d/) -  b.match(/\d/) // get first digit and compare them
        })
       console.log(words);
      }
      

      【讨论】:

        【解决方案3】:

        我不知道哪个性能更好。顺便说一句,我的每次比较都少了一个正则表达式匹配。

        var sorted = 'h2ello f3ere b1ow'.split(' ')
          .map(w => ({ key: w.match(/\d+/)[0], word: w }))
          .sort((a, b) => a.key - b.key)
          .map(o => o.word).join(' ');
        
        console.log(sorted);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-11
          • 2023-04-05
          • 2014-04-23
          • 1970-01-01
          相关资源
          最近更新 更多