I have a array of integers of type string.
var a = [\'200\',\'1\',\'40\',\'0\',\'3\'];
>>> var a = [\'2
You need to write your own sort function.
a.sort(function(a,b)) {
var intValA = parseInt(a, 10);
var intValB = parseInt(b, 10);
if (!isNaN(parseInt(a, 10))) && !isNaN(parseInt(b, 10)) {
// we have two integers
if (intValA > intValB)
return 1;
else if (intValA < intValB)
return 0;
return 1;
}
if (!isNaN(parseInt(a, 10)) && isNaN(parseInt(b, 10)))
return 1;
if (isNaN(parseInt(a, 10)) && !isNaN(parseInt(b, 10)))
return -1;
// a and b are not integers
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
});
As others said, you can write your own comparison function:
var arr = ["200", "1", "40", "cat", "apple"]
arr.sort(function(a,b) {
if (isNaN(a) || isNaN(b)) {
return a > b ? 1 : -1;
}
return a - b;
});
// ["1", "40", "200", "apple", "cat"]
Most javascript implementations, as far as I know, provide a function you can pass in to provide your own custom sorting.
Mozilla sort Method
Thanks all, though I dont know jQuery much, but from you guys examples, I summarized the code as follows which works as per my requirement
var data = ['10','2', 'apple', 'c' ,'1', '200', 'a'], temp;
temp = data.sort(function(a,b) {
var an = +a;
var bn = +b;
if (!isNaN(an) && !isNaN(bn)) {
return an - bn;
}
return a<b ? -1 : a>b ? 1 : 0;
}) ;
alert(temp);
This should be what you're looking for
var c = ['200','1','40','cba','abc'];
c.sort(function(a, b) {
if (isNaN(a) || isNaN(b)) {
if (a > b) return 1;
else return -1;
}
return a - b;
});
// ["1", "40", "200", "abc", "cba"]