[英]Javascript Sort() Array In Numeric Order
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 ? 如何拆分/匹配数组?
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/ 演示: http : //jsfiddle.net/8RNKE/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.