I'm having trouble with a javascript (node.js) sort function not sorting things in the correct order all the time. I need it to sort through negative and positive numbers and return the smallest non-negative number first. This is what I'm using right now:
.sort(function(a, b){if(a >= 0){return a - b;}else{return 1;}});
But when there is only one positive number, and it's at the end which happens often, that number is sorted as second to last. Can I have some help with a better way to implement this?
This sorting function works because it only sorts numbers if a
is on the same side of 0 as b
is:
function SortNonNegativesFirst(a,b){
if((a>=0) == (b>=0)) // Checks if both numbers are on the same side of zero
return a-b;
return a<b; // One is negative, one is positive, so return whether a is negative
}
console.log([1,6,8,4,-3,5,-2,3].sort(SortNonNegativesFirst)); //[1, 3, 4, 5, 6, 8, -3, -2]
Here's one method using the ternary operator :
alert([8,5,-1,-8,-2,7,1,10,1,7,-3].sort(function(a,b) { return a*b < 0 ? b : ab; }));
The ternary operator is a shortcut for if ... else
, so the above is equivalent to writing:
alert([8,5,-1,-8,-2,7,1,10,1,7,-3].sort(function(a,b) { if(a*b < 0) return b; else return ab; }));
This code returns true if a
and b
have different signs (positive and negative):
if(a*b < 0) return b;
If b
is positive, sort
places it before the negative a
. If b
is negative, sort
places it after the positive a
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.