Jun 20 2013

Sort observableArray of Objects in Knockout.js

Category: PHP,Programmingksg91 @ 6:32 pm

Lately, I have worked good amount of time with knockout.js and to be honest, I have been quite impressed with the dependency tracking of ko.js , no doubt, performance sucks sometime if you don’t take enough care.

Knockout.js offers a sort method for observableArray which sorts the array alphabetically (for strings) or numerically (for numbers). But consider a case when observableArray is of some objects or say you need to sort the array on some special condition. Just sort() method won’t work.

ObservableArray.sort() methods allows you to pass a function. Your function will be passed two objects and now it is up to your function how to sort them. Your function should return a negative value if first object is smaller (in your term), a positive value if first object is great, zero if both are equivalent.

For example, let’s say you have a observableArray of product object and you want to sort the array based on the price,  you may do something like this

[javascript]
function myCompareFunction(a,b){
if(a.price()<b.price()){ // if price is observable
return -1;
}else if(a.price() > b.price())
return 1;
}else {
return 0;
}
}
myObservableArray.sort(myCompareFunction);
[/javascript]

Similarly, you can sort your observableArrays. It is up to you on how you want to.

Tags: , , , , , , , ,