Inconsistent Javascript Sort

It scares me. I did a lot of sorting in Js, but for some reason I get weird behavior.

x = [{ts: "2013-09-24 14:44:22"}, {ts: "2013-09-24 14:08:26"}, {ts: "2013-09-24 17:37:42"}].sort(function(a,b) {return a.ts < b.ts;}); console.log(x); // this is sorted 

But, when I use a longer array, sorting does not work. Just look at the first three objects of the second grade:

http://jsfiddle.net/HWx7p/

Any ideas?

+4
source share
5 answers

Your comparator should return a number, not a boolean.

A negative number if less, 0 if it is equal, a positive number if more.

 .sort(function(a,b) { if(a.ts == b.ts) return 0; return a.ts < b.ts ? -1 : 1; }); 

http://jsfiddle.net/HWx7p/8/

+3
source

Try changing the sort function:

 .sort(function(a,b) { if(a.ts < b.ts) return -1; else if(a.ts > b.ts) return 1; return 0; }); 

Demo: http://jsfiddle.net/maniator/HWx7p/6/

+3
source

Sort by dates, this is what you want:

 y.sort(function(a,b) { return new Date(a.ts) < new Date(b.ts); }); 

forked fiddle http://jsfiddle.net/bHh4g/


Accidentally deleted console.log(y); in the violin, but reinsert it, showing that it is now sorted correctly.


Finally

It turns out that FireFox / Safari Date() does not match the dates in the form " 2013-09-24 14:44:22 " they need instead of y / m / d:

 y.sort(function(a,b) { var d1 = a.ts.replace(/-/g,'/'); var d2 = b.ts.replace(/-/g,'/'); d1 = new Date(d1); d2 = new Date(d2); return (d1 < d2) ? -1 : (d1 > d2) ? 1 : 0; }); console.log(y); 

forked fiddle http://jsfiddle.net/Jnx4w/
works like in Chrome / FF.

+1
source

Two things: your sort function should return a signed number, not a boolean, and it looks like you want to compare dates, not strings.

For your sort function, try:

 function(a,b){ return (new Date(a)).getTime() - (new Date(b)).getTime();} 
0
source

You are comparing a string ... no timestamp;)

 y = y.sort(function(a,b) { var ta = (+new Date(a.ts)); var tb = (+new Date(b.ts)); if (ta < tb) return -1; if (ta > tb) return 1; return 0; }); 

Here: http://jsfiddle.net/HWx7p/

-2
source

All Articles