Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout sort method doesn't work in chrome

I have an application which creates and manages activities. I use Knockout.js to hold activities in observable array. Whenever new activity is created it is inserted into an array. One of the activity properties is date. I want to order activities by date after creating new one, to display it properly in UI. This is a function I use for it:

self.Activities.unshift(activity);
self.Activities.sort(function(a, b) {
    var dateA = new Date(a.date() + " 00:00:00");
    var dateB = new Date(b.date() + " 00:00:00");
    return dateA > dateB;
});

And it works perfectly in Firefox (v 16.0.2) but doesn't work in Chrome (v 23.0.1...), Safari or IE

Why? What is the workaround? If any?

like image 640
Bartosz Avatar asked Feb 19 '23 06:02

Bartosz


2 Answers

The comparer function that you pass needs to sort needs to return a number. Some browsers are forgiving and work with a boolean.

Generally you would return -1 or 1. Something like:

return dateA > dateB ? 1 : -1;
like image 84
RP Niemeyer Avatar answered Feb 21 '23 02:02

RP Niemeyer


I was using a wrong Date format. For some reason Chrome doesn't like: d/MM/yyyy, when I used yyyy/MM/d everything works fine

like image 38
Bartosz Avatar answered Feb 21 '23 03:02

Bartosz