Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 879
MANnDAaR Avatar asked Mar 09 '26 02:03

MANnDAaR


1 Answers

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/

like image 126
VisioN Avatar answered Mar 11 '26 15:03

VisioN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!