javascript - 根据字符串中的数字对数组中的字符串进行排序

标签 javascript string sorting integer

我试图根据数组中存在的数字对字符串进行排序,即。 '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');

最佳答案

最简单的是直接对数组进行排序,而不需要拼接到其他位置未知的位置(在循环中)。

此提案使用 Array#sort使用回调查找一些小数进行排序。

var array = 'h2ello f3ere b1ow'.split(' ');

array.sort(function (a, b) {
    return a.match(/\d+/) - b.match(/\d+/);
});

console.log(array);

关于javascript - 根据字符串中的数字对数组中的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209936/

相关文章:

linux - 为什么 linux sort 没有给我想要的结果?

Python - 列表的排序列表

c++ - 尝试仅通过操作指针对链表进行排序

javascript - 无法使用 HTML5 在 Angular JS 中获取 WCF 结果

javascript - YouTube Api V3 - Videos.update - 禁止错误

javascript - 需要防止双击焦点按钮同时保持以下按钮可点击的可点击按钮表的问题

c - 使用atoi,从字符串中获取整数

string - SAS为宏变量中的所有单词添加前缀

javascript - Protractor e2e : extracting a string and assigning it to a var

javascript - 如何导出 promise 结果?