2

I'm currently rewriting the userlist implementation in an IM client interface that uses JavaScript. The names in this list are currently sorted alphabetically, and I want to edit this so that it only takes alphabetical characters in account when comparing strings.

For instance: "1foo" comes after "bar", because "foo" comes after "bar".

I know I could just create two temporary strings by removing all non-alphabetical characters from the two original strings, but I'm guessing that there must be easier ways to do this.

4
  • Can you post the code you're currently using to sort? Commented Jan 23, 2012 at 22:15
  • Do you want the strings starting with numbers sorted before or after strings with letters? What do you want to happen? Commented Jan 23, 2012 at 22:15
  • You can use custom sort functions in javascript: javascriptkit.com/javatutors/arraysort.shtml Commented Jan 23, 2012 at 22:15
  • I'd just use a regex to get only alphabetic chars and compare those. I believe that there are some callback versions of the string find functions that could be used too. Commented Jan 23, 2012 at 22:16

1 Answer 1

8

Well, if you have an array of strings called arr, you can use this one-liner:

arr.sort(function(a,b) {return a.replace(/[^a-z]/ig,'') > b.replace(/[^a-z]/ig,'') ? 1 : -1;});

arr is now sorted taking only letters into account.

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

1 Comment

Just a note that if the array is a large array, this sort could be really, really slow because two regular expression replace operations resulting in temporary creation of strings would occur on every comparison in the sort algorithm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.