Sorting an observable array, which has queried data returned by breezeJS

169 views Asked by At

Image of an observableArray coming while queryinq database using breeze

The above image is of observableArray which is coming while queryinq database using breezeJS (using EntityManager).

My question is that

how do we sort this observable based on some criteria i.e., (object.attributeName) ?

So that this array is sorted based on some attribute name and we can simply use the observable within foreach bindings and use them in sorted way because I don't wanna query all the time (locally or from server) to get data in sorted order.

1

There are 1 answers

1
spender On BEST ANSWER

So make a computed

var orderDirection = ko.observable(1);
var orderField = ko.observable("id");
var orderedObsArr = ko.computed(function(){
     var oDir = orderDirection();
     var oField = orderField();
     var newArr = originalObsArr().slice(0);
     newArr.sort(function(a,b){
         return oDir * (a[oField] > b[oField] ? 1 : -1);
     });
     return newArr;
});

so to change to a sort by name descending, you simply change:

orderDirection(-1);
orderField("name");

and your computed dependent orderedObsArr will be updated.

See this pen for a working example.