3

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
  • "78em", "145px" : those are different units. Why this sort ? Do you want it independently of the unit or should em to pixel conversion occurs ? Commented Aug 30, 2012 at 7:59

1 Answer 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/

Sign up to request clarification or add additional context in comments.

2 Comments

I would add i so it doesn't only check for lowercase, making it safer.
@sQVe Good catch. There is also an option to leave only digits using /[\D]/g. However, it depends on the input.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.