Apply Sort Function on Observable Array Using KnockoutJS

In today's article I will tell you how to apply a Sort Function on an Observable Array using KnockoutJS.

Introduction

In my previous article I explained:

In today's article I will tell you how to apply a Sort Function on an Observable Array using KnockoutJS.

The Sort function is used to sort the data present in the Array, in the sorted Array we pass another function that returns the value by comparing them.

Step 1

First of all you need to add an external Knockout js file into your application, you can either download it from this link: "KnockoutJS" or can download my application available at the beginning of this article in Zip Format and then use the file attached with this Zip file.

After downloading the file you need to call it in the head section of your application.

<head runat="server">

    <title></title>

    <script src="knockout-2.3.0.js"></script>

</head>

Step 2

Now we can work on our application. First we will work on the ViewModel. For that you need to add a Script tag under the Body Section and then need add this code:

        <script>

            function x() {

                var self = this;

                self.trainee = ko.observableArray([

                    { name: 'Anubhav' },

                    { name: 'Mohit' },

                    { name: 'Ashish' },

                    { name: 'Sammy' },

                    { name: 'Brijesh' }

                ]);

    

                self.sortPeople = function () {

                    self.trainee.sort(function(left, right) { 

                        return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1) 

                    });

                }

            }

            ko.applyBindings(new x());

        </script>

Here first I created a function named "x()".

In this function I created an object named "self" that will represent the current function.

Then I created an Observable Array named "Trainee()". In this Array I provided three names as default names.

Then a function is created named "sortPeople", in this function one more function is created, the sort function. In this sort function, two objects are accepted from the array that will return the negative value. If the first argument is smaller then it will return a positive value, if the first argument is bigger. If the values are the same then zero will be returned.

At the end I applied the Binding to the x().

Step 3

Our work on the ViewModel is now completed so we can move towards the View of our application.

Write this code in the view part of your application:

        <input type="button" data-bind="click:sortPeople" value="Click me"/>

                <ul data-bind="foreach: trainee">

            <li data-bind="text:name"></li>

            </ul>

Here I simply created a button bound to the sortPeople function, this function is bound to the click event of this button.

Then I created an Unordered List that is bound to the Array "tarinee".

So, now what will happen is that at run time all the employees will be seen in the same order as they are declared but as you click on the button, all the names will be sorted.

The complete code of this application is as follows:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="knockout-2.3.0.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <input type="button" data-bind="click:sortPeople" value="Click me"/>

                <ul data-bind="foreach: trainee">

            <li data-bind="text:name"></li>

            </ul>

        <script>

            function x() {

                var self = this;

                self.trainee = ko.observableArray([

                    { name: 'Anubhav' },

                    { name: 'Mohit' },

                    { name: 'Ashish' },

                    { name: 'Sammy' },

                    { name: 'Brijesh' }

                ]);

    

                self.sortPeople = function () {

                    self.trainee.sort(function(left, right) { 

                        return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1) 

                    });

                }

            }

            ko.applyBindings(new x());

        </script>

    </form>

</body>

</html>

Output

On running the code you will get output like this:

sort function knockout1

But as you click on the button then all the names will be sorted.

sort function knockout2