JsTree: How to sort jstree nodes with folders at the top

Aminesrine picture Aminesrine · Dec 9, 2016 · Viewed 9.3k times · Source

I use the plugin Jstree to draw a tree of folders ans files.

I want to get the list of folders at the top then the list of files (the list of folders and files must be sorted in alphabetical order).

There is my function of initilization of the tree:

$('#jstree_demo_div').jstree({ 
    'core' : {
        'data' : [

            {"id":"index_0","text":"test_folder","parent":"#","icon":""},
            {"id":"index_1","text":"vide","parent":"index_0","icon":""},
            {"id":"index_2","text":"05nesf-sdfdgd.mp4","parent":"index_1","icon":"fa fa-film"},
            {"id":"index_3","text":"naissance-d-une-fleur-ouwzp9me-41.mp4","parent":"index_0","icon":"fa fa-film"},
            {"id":"index_4","text":"za05nesfsdfsdg.mp4","parent":"index_0","icon":"fa fa-film"},
            {"id":"index_5","text":"ddd","parent":"#","icon":""},
            {"id":"index_6","text":"05nes-ibw6q9me-41.mp4","parent":"index_5","icon":"fa fa-film"},
            {"id":"index_7","text":"tom-jerry-soundscape-ttar8gme-41.mp4","parent":"#","icon":"fa fa-film"},
            {"id":"index_8","text":"aaes-qmc8q-9me-41.mp4","parent":"#","icon":"fa fa-film"},
            {"id":"index_9","text":"bb05nes.mp4","parent":"#","icon":"fa fa-film"}
        ]
    },
    'plugins' : ['sort','types'],
    'sort' : function(a, b) {
        //What is the function of sorting
    },
});

the result of my initialisation : Tree

What function of sorting I need to use?

Answer

Alexandre Tranchant picture Alexandre Tranchant · Dec 9, 2016

You can sort by icon and after by text :

'sort' : function(a, b) {
        a1 = this.get_node(a);
        b1 = this.get_node(b);
        if (a1.icon == b1.icon){
            return (a1.text > b1.text) ? 1 : -1;
        } else {
            return (a1.icon > b1.icon) ? 1 : -1;
        }

Here is a jsfiddle