Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
KnockoutJS Web Development

You're reading from   KnockoutJS Web Development Efficiently work with data, web templates, and custom HTML tags using KnockoutJS

Arrow left icon
Product type Paperback
Published in Feb 2015
Publisher
ISBN-13 9781782161028
Length 178 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
John Farrar John Farrar
Author Profile Icon John Farrar
John Farrar
Arrow right icon
View More author details
Toc

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...
You have been reading a chapter from
KnockoutJS Web Development
Published in: Feb 2015
Publisher:
ISBN-13: 9781782161028
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 $19.99/month. Cancel anytime
Banner background image