Jas*_*han 2 arrays sorting knockout.js momentjs
我有一个存储在一个对象的数组observableArray,每个数组项都是moment.js日期的对象.
{startDate:momentObject, endDate:momentObject, cycle:null}
我需要计算两件事.一个是startDates之间的平均时间.我认为最简单的方法是计算数组中最早和最晚的startDates之间的持续时间,并将其除以条目总数.
我还需要2个startDates之间的时间段.我提出的快速解决方案是这样的:
$.each(dateArray, function(index, item){
    var previousItem = dateArray[index - 1];
    if(previousItem){
      // since these are moment objects, just use the diff method
      return item.cycle = previousItem.startDate.diff(item.startDate, 'days');
    }
    return false;
});
但这需要observableArray按升序排序.所以这是我的问题.
observableArray被强制排序,每次我推新的项目呢?startDates中间期间和中间期间?您可以向obervableArray添加订阅事件处理程序,如下所示:
self.MyArray = ko.observable([]);
var myArraySubscription = self.MyArray.subscribe(onMyArrayChange);
function onMyArrayChange(){
    //Remove the subscription before sorting, to prevent an infinite loop
    myArraySubscription.dispose();
    myArraySubscription = null;
    //Force a sort of the array here. 
    self.MyArray.sort();//NOTE: You need to define your sorting logic here...this line is just a placeholder
    //Re-subscribe
    myArraySubscription = self.MyArray.subscribe(onMyArrayChange);
}