如何按javascript中的最后一个数字字符对文本数组进行排序

时间:2014-03-13 13:27:26

标签: javascript arrays sorting

我有一系列文字,例如[building2, building1 , building3, building5, building4]

如何按最后一个数字字符对此数组进行排序,因此已排序的数组将为building1, building2, building3, building4, building5, building6

4 个答案:

答案 0 :(得分:3)

var array = ["building200", "building10", "building3", "building5", "building4"];

array.sort(function(a, b){
  var char1 = a.substr(a.search(/\d+$/));  // get the last numbers
  var char2 = b.substr(b.search(/\d+$/));   // get the last numbers
  return parseInt(char1) - parseInt(char2); // sort by parsing to number
});

alert(array); // ["building3", "building4", "building5", "building10", "building200"]

a.search(/\d/)将返回遇到的第一个数字的索引,a.substr(that_index)将从那里剪切字符串直到结束。

如果数组包含长度不均匀的字符串,例如["buildingsss2", "buildisng1", "building3", "building5", "builsding4"]

,也会有效

希望有所帮助!

答案 1 :(得分:3)

您可以使用正则表达式\d+来获取所有连续数字,然后通过从另一个中减去一个来比较这两个元素,例如

var data = [ 'building2', 'building10', 'building3', 'building5', 'building4' ];

data.sort(function(first, second) {
    return /\d+/.exec(first)[0] - /\d+/.exec(second)[0];
});

console.log(data);

<强>输出

[ 'building2', 'building3', 'building4', 'building5', 'building10' ]

注意:这比现在发布的其他解决方案更好,因为即使数字大于9,这也可以正常工作。

答案 2 :(得分:2)

使用.sort()方法

var a = ['building2', 'building1' , 'building3', 'building5', 'building4'];
console.log(a.sort());

输出

["building1", "building2", "building3", "building4", "building5"] 

不需要自定义功能

答案 3 :(得分:2)

Array.sort,使用:

['building2', 'building1', 'building3', 'building5', 'building4']. 
  sort(function(a,b){
         return +( /\d{1,}$/.exec(a) || [0] )[0] - 
                +( /\d{1,}$/.exec(a) || [0] )[0]; 
       }
  );

通过这种方式,您还可以对多于10个建筑物进行分类,如中 ['building1', 'building12', 'building302', 'building205', 'building400']
并包括不以数字值结尾的字符串