Knockout - Moment - date filter grouping
HTML
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<script src="https://raw.github.com/timrwood/moment/1.6.2/moment.js"></script>
<ul data-bind="foreach: days">
<li>
<span data-bind="text: formattedDate"></span>
</li>
</ul>
JavaScript
var TimeSlot = function(date, id) {
this.thedate= ko.observable(date);
this.id = ko.observable(id);
}
var timeslots = ko.observableArray([
new TimeSlot(new Date(2012, 4, 4, 14, 0, 3, 0), 5),
new TimeSlot(new Date(2012, 4, 1, 3, 0, 4, 0), 3),
new TimeSlot(new Date(2012, 4, 1, 8, 0, 10, 0), 1),
new TimeSlot(new Date(2012, 4, 4, 4, 0, 5, 0), 4),
new TimeSlot(new Date(2012, 4, 1, 2, 0, 1, 0), 2),
new TimeSlot(new Date(2012, 4, 6, 5, 0, 7, 0), 6)
]);
var filteredDays = ko.computed(function () {
var index= {},
result = []
//make one pass through timeslots.
//maintain an index object to save on looping (indexOf)
//build the result as we go
ko.utils.arrayForEach(timeslots(), function(slot) {
var
date = moment(moment(slot.thedate()).format('MM-DD-YYYY')).toDate(),
day = moment(date).format('ddd MMM DD')
if (!index[day.toString()]) {
result.push({dateOnly: date, formattedDate: day})
index[day] = true
}
});
console.log(result)
return result.sort(function(a, b){ return a.dateOnly > b.dateOnly })
});
ko.applyBindings({ days: filteredDays });