Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
KnockoutJS Web Development

You're reading from  KnockoutJS Web Development

Product type Book
Published in Feb 2015
Publisher
ISBN-13 9781782161028
Pages 178 pages
Edition 1st Edition
Languages

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:

  1. The sort function passes in two structures. Each structure matches the items being sorted. The variable name could be anything; we choose left and right 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.

  2. The basic return value for sort needs to be true or false. This tells the program whether the two...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}