bflemi3 bflemi3 - 1 month ago 6
Javascript Question

Computed that returns a sorted observableArray

I have a computed observable that returns a filtered, sorted version of my

observableArray
but the sort is not working at all.

Here is My fiddle

String.prototype.contains = function (value) {
return this.indexOf(value) != -1;
};

function Item(data) {
this.name = ko.observable(data);
}

function ViewModel() {
var self = this;
this.items = ko.observableArray([new Item('John'), new Item('Pat')]);
this.filterValue = ko.observable();

this.filteredItems = ko.computed(function() {
var filterValue = self.filterValue();

if(!filterValue)
return self.items();

return ko.utils.arrayFilter(self.items(), function(){
return item.name().toLowerCase().contains(filterValue.toLowerCase());
}).sort(function(a,b){
return a.name == b.name ? 0 : (a.name < b.name ? -1 : 1);
});
});
}


THE ANSWER
Here's the update fiddle

Answer

As @Paul Manzotti noted, your sort function is not accessing the "name" properties correctly. In addition, your "filterValue" is undefined, so your function exits before it gets to the sort.

Something like this will make it work:

    var filtered = filterValue ? ko.utils.arrayFilter(self.items(), function(item){
        return item.name().toLowerCase().contains(filterValue.toLowerCase());
    }) : self.items();

    return filtered.sort(function(a,b){
        return a.name() == b.name() ? 0 : (a.name() < b.name() ? -1 : 1);
    });
Comments