Reputation: 1947
I have a array of integers of type string.
var a = ['200','1','40','0','3'];
>>> var a = ['200','1','40','0','3'];
console.log(a.sort());
["0", "1", "200", "3", "40"]
I'll also have a mixed type array. e.g.
var c = ['200','1','40','apple','orange'];
>>> var c = ['200','1','40','apple','orange']; console.log(c.sort());
["1", "200", "40", "apple", "orange"]
==================================================
The integers of string type gets unsorted.
Upvotes: 4
Views: 13776
Reputation: 2064
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"]
Upvotes: 6
Reputation: 1492
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"]
Upvotes: 18
Reputation: 1947
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);
Upvotes: 0
Reputation: 6522
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;
});
Upvotes: 1
Reputation: 1230
Most javascript implementations, as far as I know, provide a function you can pass in to provide your own custom sorting.
Upvotes: -1