KnockoutJS observable arrays offer a sorting function, so it is relatively easy to sort a data array in your user interface (regardless of the natural order of the data).
data-bind="foreach: items.sort(function (l, r) { return l.lastName() > r.lastName() ? 1 : -1 })"
You do not need to pre-sort / re-sort the original data, if you sort before binding (or re-sorting due to sorting) then you are doing it wrong.
However, what you ask for is sorting by two values, last name, then first name.
Instead of "l.lastName ()> r.lastName ()? 1: -1", consider the following:
l.lastName()
It may be more effective, I'm sure. Basically, you have three conditional expressions:
- Are the last names equal?
- If so, compare the names and return the result.
- Repeat, compare last names and return the result.
I looked at your code and I do not see such sorting function.
This is similar to Michael Best's answer, however, I tried to clarify WHERE in order to handle the sorting (in your example bindings, the first example) and HOW to achieve the view you are looking for (multiple anchor points).
data-bind="foreach: items().sort(function (l, r) { return (l.lastName() == r.lastName()) ? (l.firstName() > r.firstName() ? 1 : -1) : (l.lastName() > r.lastName() ? 1 : -1) })"
Naturally, this can become cumbersome as you enter more sorting vectors, such as inverse or additional data, and therefore you must implement a filter function that performs the above assessment for you:
data-bind="foreach: items().sort(my.utils.compareItems)"
x4d Jan 25 '13 at 0:21 2013-01-25 00:21
source share