Answer the question
In order to leave comments, you need to log in
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
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question