Using javascript sort()
method, I am trying to do sorting a list but sorting have in a group of even numbers and odd numbers.
The code which I tried is work
Change the code as follows:
n.sort(function(a,b){
if (a % 2 != b % 2 ){
return a%2;
}else {
return (a - b) > 0 ? 1 : -1;
}
});
Working sample is here.
Edit:
n.sort(function(a,b){
if (a % 2 != b % 2 ){
return a%2 == 0 ? -1 : 1; // this is the fix :)
}else {
return (a - b) > 0 ? 1 : -1;
}
});
Edit 2: I've modifed the code for negative numbers. See working sample.
n.sort(function(a,b){
if (a % 2 != b % 2 ){
return Math.abs(a)%2;
}else {
return a > b ? 1 : -1;
}
});