67

I have an observable array in Knockout of person objects. I wanted to be able to sort the list of persons based on the last name. The problem is the list has a number of duplicate last names. The result is that when there are more than one last name, the first names appear as they were found. I'd like to be able to sort the array by last name and when there are more than one last name, have it also sort by first name. I'm using a text input for the user to start typing in the last name. The results are bound to a template that displays all the matches.

<input data-bind="value: filter, valueUpdate: 'afterkeydown'">

And here is my Knockout array filter code:

function Item(firstname, lastname) {
     this.firstname = ko.observable(firstname);
     this.lastname = ko.observable(lastname);
}

var playersViewModel = {
     items: ko.observableArray([]),
     filter: ko.observable("")
};
var players;

$(function() {
    playersViewModel.filteredItems = ko.computed(function() {
         var filter = this.filter().toLowerCase();
         if (!filter) {
              return this.items();
         } else {
              return ko.utils.arrayFilter(this.items(), function(item) {
                    return ko.utils.stringStartsWith(item.lastname().toLowerCase(), filter);
              });
         }
    }, playersViewModel);

    $.getJSON('./players.json', function(data) {
        players = data.players;
        playersViewModel.players = ko.observableArray(players);
        ko.applyBindings(playersViewModel);    
        var mappedData = ko.utils.arrayMap(players, function(item) {
             return new Item(item.firstname,item.lastname);
        });
        playersViewModel.items(mappedData);
    });    
});

For last name filtering this works fine, but I'm unable to find a way to add in sorting first name when there are duplicate last names. For example, in my array when sorted by last name I'm getting:

Joe Bailey
Jack Brown
Adam Brown
Bob Brown
Jim Byrd

I'd like the duplicate last names to have their first names sorted as well:

Joe Bailey
Adam Brown
Bob Brown
Jack Brown
Jim Byrd

4 Answers 4

108

KnockoutJS observable arrays offer a sort function, this makes it relatively easy to sort a databound array in your UI (regardless of the natural order of the data.)

data-bind="foreach: items.sort(function (l, r) { return l.lastName() > r.lastName() ? 1 : -1 })"

You should not have to pre-sort/re-sort your source data, if you're sorting before binding (or rebinding due to a sort) then you're doing it wrong.

That said, what you're asking is to sort by two datum, last name, then first name.

Instead of "l.lastName() > r.lastName() ? 1 : -1" consider the following:

l.lastName() === r.lastName() 
    ? l.firstName() > r.firstName() ? 1 : -1
    : l.lastName() > r.lastName() ? 1 : -1

This could be more efficient, I'm sure. Basically you have three conditionals at play:

  1. Are the last names Equal?
  2. If so, compare first names and return a result.
  3. Else, compare last names and return a result.

I've scanned your code and I see no such sort function in place.

This is similar to Michael Best's answer, however, I've attempted to clarify WHERE to handle sorting (in your binding, first example) and HOW to achieve the sort you're looking for (multiple datum.)

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 get unwieldy as you introduce more sort vectors, such as reversals or additional datum, and so you should implement a filter function that performs the above evaluation for you:

data-bind="foreach: items().sort(my.utils.compareItems)"
6
  • 2
    I have this same issue and thanks for your answer. I was able to get my array sorted with the filter function approach. However, I'm finding that the array won't automatically resort if the datum is updated (its an observable). What am I doing wrong?
    – 828
    Feb 26, 2013 at 1:26
  • 1
    See this fiddle jsfiddle.net/RbX86 and this fiddle jsfiddle.net/RbX86/1 - this first shows how you can separate your sort() from your binding, and the second shows how you can initiate a re-bind/re-evaluation of your observableArray after data has changed (via valueHasMutated()) - take note of how the observable array is sorted in the first fiddle, whereas the underlying array (not the observable) is sorted in the second example. These fiddles are from stackoverflow.com/questions/10480118/… Feb 26, 2013 at 20:04
  • 17
    Works for me, but I had to use items().sort(...) instead of items.sort(...)
    – Fabrice
    Aug 12, 2013 at 16:08
  • 3
    I found that displaying the initial list worked fine with items.sort, however if I pushed a new item to the observable array it wouldn't show up unless I used items().sort(), so +1 to Fabrice's suggestion, and the original answer should be updated.
    – Justin
    Apr 16, 2014 at 19:15
  • 4
    I recently opened an issue in Github for Knockout to better handle the sorting situation: github.com/knockout/knockout/issues/1380 Apr 17, 2014 at 23:56
3

If you make sure your players.json returns the names sorted, you'll be fine. If it's loading them from a database, you need to add the first name field to your ORDER BY clause.

If you want to do the sorting in Javascript, you could do it right after you load it from the service:

players.sort(function(player1, player2) {
    return player1.lastname.localeCompare(player2.lastname) ||
        player1.firstname.localeCompare(player2.firstname);
});
3
  • Actually, I get the players through a Web service where they are sorted by team. My problem is I'm also allowing the user to sort players by position, points and other properties, so being able to resort the names properly by last name is important in this case. Oct 4, 2012 at 3:06
  • Your code doesn't include any sorting. So how are they sorted by last name already? Anyway, I added an example of sorting by last and first name using Javascript. Let me know if you need anything else. Oct 4, 2012 at 20:44
  • Any update? If this helped you fix your problem, please accept it. If not, please let me know what else is going on. Oct 8, 2012 at 20:00
0

I had some issues trying to sort a observable array, I was not seeing any results in my code.

You need to sort the results you receive via ajax/getJSON request first, before you return the new items into your array.

This way the results are sorted before they are added into your observable array as new items. No need to sort them at the bindings then.

See the example below.

players(ko.utils.arrayMap(result, function (item) {
                    result.sort(function (l, r) {
                        return l.name == r.name ? 0 : (l.name < r.name ? -1 : 1);
                    });
                return new Player(item);
            }));
  1. get data using AJAX / getJSON
  2. Sort the result of that request into your array of choice
1
  • the only problem with this approach is that introducing new data client-side would result in unsorted results, and therefore would require manual re-sort in response to changes in the observable array -- this defeats some value in using ko.observableArray -- though, yes, JavaScript sort() does sort arrays -- it's also worth noting part of the original problem was not the binding method but instead the need to sort on multiple extents (OP was only sorting by last name, resulting in indeterminate/natural order when multiple persons had the same last name -- ie. Adam, Bob, and Jack.) Mar 29, 2017 at 20:39
-4

You have to use Two sort to do this .In first sorting , sort according to persons last name And In 2nd Sorting first Search according to last name if more than two persons have same last name than sort these according to their first name at their location , using some Standard sorting Algorithm ....

1
  • 1
    Sorry, sonu, but this is not correct or illuminating. Jun 15, 2014 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.