Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question
 
"78em", "145px" : those are different units. Why this sort ? Do you want it independently of the unit or should em to pixel conversion occurs ? –  dystroy Aug 30 '12 at 7:59
 
What have you tried? –  Klas Lindbäck Aug 30 '12 at 8:00
add comment

1 Answer

up vote 8 down vote accepted

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/

share|improve this answer
1  
Clean and simple :) –  Snake Eyes Aug 30 '12 at 7:58
1  
I would add i so it doesn't only check for lowercase, making it safer. –  sQVe Aug 30 '12 at 8:01
 
@sQVe Good catch. There is also an option to leave only digits using /[\D]/g. However, it depends on the input. –  VisioN Aug 30 '12 at 8:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.