Javascript Sort()数组以数字顺序排列

时间:2022-07-21 16:02:40

I have array like this

我有这样的数组

var Arr = [ 'h78em', 'w145px', 'w13px' ]

I want to sort this array in Numerical Order

我想按数字顺序对这个数组进行排序

[ 'w13px', 'h78em', 'w145px' ]

For Regular Numerical sorting I use this function

对于常规数值排序,我使用此功能

var sortArr = Arr.sort(function(a,b){
     return a-b;
});

But due to word character in the array this function doesn't work

但由于数组中的单词字符,此功能不起作用

Is it possible to sort this array ? How do I split/match array ?

是否可以对此数组进行排序?如何拆分/匹配数组?

1 个解决方案

#1


8  

You can use regular expression to remove all letters when sorting:

您可以使用正则表达式在排序时删除所有字母:

var Arr = [ 'h78em', 'w145px', 'w13px' ]​;
var sortArr = Arr.sort(function(a, b) {
    a = a.replace(/[a-z]/g, "");  // or use .replace(/\D/g, "");
    b = b.replace(/[a-z]/g, "");  // to leave the digits only
    return a - b;
});

DEMO: http://jsfiddle.net/8RNKE/

#1


8  

You can use regular expression to remove all letters when sorting:

您可以使用正则表达式在排序时删除所有字母:

var Arr = [ 'h78em', 'w145px', 'w13px' ]​;
var sortArr = Arr.sort(function(a, b) {
    a = a.replace(/[a-z]/g, "");  // or use .replace(/\D/g, "");
    b = b.replace(/[a-z]/g, "");  // to leave the digits only
    return a - b;
});

DEMO: http://jsfiddle.net/8RNKE/