javascript - Sort with custom function giving reversed results -


i have following array (here shown json):

[{     "value": -1,     "absolute": false,     "calltime": 0 }, {     "value": 23,     "absolute": true,     "calltime": 1365179295887 }, {     "value": 1,     "absolute": false,     "calltime": 0 }, {     "value": 1,     "absolute": true,     "calltime": 0 }] 

i need sort array putting objects highest values of calltime property @ top of array.

i use following code (based on explanation of subject offered mdn):

var handlers = json.parse("[...]");  handlers.sort(function(firsthandler, secondhandler) {     if (firsthandler.calltime < secondhandler.calltime) {         return -1; // sort firsthandler lower index secondhandler.     } else {         return 1; // sort secondhandler lower index firsthandler.     }      return 0; });  console.log(json.stringify(handlers)); 

after running function, following output:

[{     "value": 1,     "absolute": true,     "calltime": 0 }, {     "value": 1,     "absolute": false,     "calltime": 0 }, {     "value": -1,     "absolute": false,     "calltime": 0 }, {     "value": 94,     "absolute": true,     "calltime": 1365179553381 }] 

which seems inverse of i'm expecting (notice how object calltime different 0 @ bottom).

i think there might missing big here, or maybe i'm misled, changing body of function to:

return firsthandler.calltime - secondhandler.calltime 

should give correct results, yet doesn't seem to.

what doing wrong?

your sort function incorrect. logic reversed, because sort function indicating elements smaller values of calltime come first, whereas want larger values @ top of array. also, return -1 or 1, , never 0. should return 0 when elements tied.

rewrite follows:

handlers.sort(function(firsthandler, secondhandler) {     if (firsthandler.calltime > secondhandler.calltime) {         return -1; // sort firsthandler lower index secondhandler.     } else if (firsthandler.calltime < secondhandler.calltime) {         return 1; // sort secondhandler lower index firsthandler.     }      return 0; // sort firsthandler , secondhandler equal }); 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -