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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With