Sorting in Tree

Tree allows you to sort nodes on the client side. Note, along with the parent nodes, child nodes are sorted as well.

Data are sorted as strings and by levels, starting from the latest nesting level.

Common

Sorting in Tree can be invoked by calling the sort method. The method can be called on some event or action, i.e. a button click or page load.

Sorting Tree on button click

<input type='button' onclick='tree.sort("#value#", "asc");'>
 
<script type="text/javascript" charset="utf-8">
    tree = webix.ui({ view:'tree', ...})
</script>

Related sample:  Sorting in Tree

Custom Sorting Functions

If you want to apply custom sorting behavior, define the related logic in a function and invoke this function in the sort method.

This function is called for each pair of adjacent values and return 1,-1 or 0:

  • 1 - an object with the first value in pair must go before the second one;
  • -1 - the second object goes before the first one;
  • 0 - the order of both objects doesn't change.

Let's assume you have a tree like this:

And want to sort only car makers (the second level) and keep the models (the third level) as they are. As the default sorting affects all nodes, you need to provide custom logic. It may look as in:

Sorting the tree by one level

{ view: 'button', value:'sort car makers', click(){
    tree.sort(sortMakers);
}}
...
function sortMakers(a,b){
    if (a.$level == 2) {
        a = a.value;
        b = b.value;
        return a > b ? 1 : (a < b ? -1 : 0);
    } else {
        return 0;
    }
}

Note that Tree sorts data by levels starting from the latest nesting level, i.e. first car models of each maker are sorted, then car makers themselves.

Related sample:  Custom Sorting in Tree

Back to top