A
A
Alexey Ogonkov2012-08-06 15:19:36
JavaScript
Alexey Ogonkov, 2012-08-06 15:19:36

Ways to sort mixed array data?

You need to sort an array consisting of mixed data (strings, but if necessary, you need to recognize that "1" is 1). So far I've come to this decision :

function doCompare(a, b) {
  var first_int = parseInt(a, 10);
  var second_int = parseInt(b, 10);
  
  if (isNaN(first_int) && isNaN(second_int)) {
    var str_one = a.toLocaleLowerCase();
    var str_two = b.toLocaleLowerCase();

    return str_one.localeCompare(str_two);
  } else if (isNaN(first_int)) {
    return 1;
  } else if (isNaN(second_int)) {
    return -1;
  } else {
    return a - b;
  }
}
Are there elegant solutions to the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wott, 2012-08-06
@Wott

Well offhand

function doCompare(a, b) {
  var r = a-b;

  if (isNaN(r)) {
    r = isNaN(a)-isNaN(b);
    if (r == 0) {
      r = a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase());
    }
  }

  return r;  
}

The feature will be that it recognizes numbers in the form of hex and so on :)
In general, it was normal, although it is not clear why such a comparison.
If the profile says that the function is critical , then you need to look at what is more common and redo it so that the more common one would be the first in the checks. What I have above works better if there are a lot of numbers.
If there was no profiling and in general it's for the sake of art, then it's better not to touch it :)

A
Anatoly, 2012-08-06
@taliban

What do you personally dislike about this solution? You after all not each ask. So there is something specific here that is bothering you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question