SpreadJS Documentation
Sorting Data
SpreadJS Documentation > Developer's Guide > Managing Data > Sorting Data

You can sort data in the widget and specify a column or row index to sort on as well as the sort criteria. You can also specify multiple sort keys (sort by a specified column or row first, then another column or row, and so on).

Use the sortRange method to sort data. Use the sortInfo object in the sortRange method to specify sort keys and ascending or descending order.

Using Code

Select one of the buttons to sort the first column.

JavaScript
Copy Code

var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"),{sheetCount:3});
var activeSheet = spread.getActiveSheet();
activeSheet.setValue(0, 0, 10);
activeSheet.setValue(1, 0, 100);
activeSheet.setValue(2, 0, 50);
activeSheet.setValue(3, 0, 40);
activeSheet.setValue(4, 0, 80);
activeSheet.setValue(5, 0, 1);
activeSheet.setValue(6, 0, 65);
activeSheet.setValue(7, 0, 20);
activeSheet.setValue(8, 0, 30);
activeSheet.setValue(9, 0, 35);

$("#button1").click(function(){
     //Sort Column1 by ascending at every button click.
    activeSheet.sortRange(-1, 0, -1, 1, true, [{index:0, ascending:true}]);
   });

 $("#button2").click(function(){
    //Sort Column1 by descending at every button click.
     activeSheet.sortRange(-1, 0, -1, 1, true, [
       {index:0, ascending:false}
     ]);
 });
//Add button controls to page
<input type="button" id="button1" value="button1"/>
<input type="button" id="button2" value="button2"/>

Using Code

Select the button to sort using the sort criteria specified by the sortInfo object.

JavaScript
Copy Code
activeSheet.setRowCount(6);
activeSheet.setValue(0, 0, 10);
activeSheet.setValue(1, 0, 100);
activeSheet.setValue(2, 0, 100);
activeSheet.setValue(3, 0, 10);
activeSheet.setValue(4, 0, 5);
activeSheet.setValue(5, 0, 10);
activeSheet.setValue(0, 1, 10);
activeSheet.setValue(1, 1, 40);
activeSheet.setValue(2, 1, 10);
activeSheet.setValue(3, 1, 20);
activeSheet.setValue(4, 1, 10);
activeSheet.setValue(5, 1, 40);

    $("#button1").click(function(){
        //Create a SortInfo object where 1st key is column 1 and the 2nd key is column 2.
        var sortInfo = [
            {index:0, ascending:true},
            {index:1, ascending:true}];
        ///Execute sorting which targets all rows based on the created sorting conditions.
        activeSheet.sortRange(0, -1, 6, -1, true, sortInfo);
    });

//Add button control to page
<input type="button" id="button1" value="button1"/>