The fifth feature of our to-do application is to give users the ability to sort our list of tasks by priority and name. We will do this by adding the buttons, which will sort the tasks when clicked upon. This feature will demonstrate the built-in sort function of Knockout.
We will use the sort
function of the observable array to sort our tasks. The following is the simplest example of using the sort
function:
observableArray.sort();
This will sort observableArray
alphabetically. This simple sort
function is ideal for arrays of strings or numbers, but for an array of objects, such as our tasks
array, we need to tell the sort
function how it should compare objects. To do this, we pass a function to the sort
function that accepts two objects and returns either a 0, 1, or -1. It should return a 0 if the two objects are equal, 1 if the second object is smaller, and -1 if the first object is smaller. Here is an example which sorts an array of person object by their...