Sorting time
Displaying data is a very common use case for web pages. Perhaps the most common function people perform on data besides searching is sorting. We are going to look at how to sort data based on particular data fields. This time, we will create the logic first. Enter the following code into the script
tag:
function doSort() { myVM.employee.sort(function (left, right) { return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1); }); }
We will break down the logic for those unfamiliar with this level of JavaScript:
- The
sort
function passes in two structures. Each structure matches the items being sorted. The variable name could be anything; we chooseleft
andright
because it helps the programmer remember which variable is which. You can use, of course, any variable naming you choose. Each variable contains the whole structure of the item being passed in. - The basic return value for
sort
needs to be true or false. This tells the program whether the two...