Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - Custom sort function kendo grid

Can anyone please let me know how can we write our own function in javascript for sorting in kendo grid. And do we need to write two functions for asc and desc?

Any help.. greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it and you don't have to write two different function for ascending and descending since the only thing that you need to do is providing a compare function for the column field that you need a special algorithm.

Example:

Lets assume that we want to sort a grid by name (a string) and this is our data:

data    : [
    { id : 1, name : "john" },
    { id : 2, name : "jane" },
    { id : 3, name : "Jane" },
    { id : 4, name : "jack" },
    { id : 5, name : "jane"?},
    {?id : 6, name : "janette" },
    {?id : 7, name : "John" }
],

and the columns definition as:

columns   : [
    { field: "id", title: "id" },
    { field: "name", title: "Name"}
]

What we get is:

id   Name
4    jack
2    jane
5    jane
3    Jane
6    janette
1    john
7    John

As we see we get it sorted alphabetically mixing lower and uppercase but lowercase always come before uppercase.

If we want to sort it first upper and then lowercase (ASCII order), we should define columns.sortable.compare for name as:

columns   : [
    { field: "id", title: "id" },
    { 
        field: "name", 
        title: "Name",
        sortable: {
            compare: function (a, b) {
                return a.name === b.name ? 0 : (a.name > b.name) ? 1 : -1;
            }
        }
    }
]

The compare function receives two items to compare.

Now, what we get is:

id   Name
3    Jane
7    John
4    jack
2    jane
5    jane
6    janette
1    john

You can try it both for ASC and DESC here Simple and neat!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...