Custom Sorting of Rows in a Table
Jump to navigation
Jump to search
This example uses JavaScript to sort the rows of a table according to a custom sort order based on the row labels.
This example can be run in C:\Program Files\Q\Examples\Cola.Q (this may be located on a different place on your computer depending upon how Q was installed). Create a table of Q5. Brand associations by SUMMARY.
var labels = ['Pepsi Max','Coke Zero','Pepsi Light','Diet Coke','Pepsi','Coca Cola'];
var last_index = null;
for (var i = 0; i < labels.length; i++) {
table.moveRowAfter(table.rowIndex(labels[i]), last_index);
last_index = table.rowIndex(labels[i]);
}
Note that:
- The order of the rows is specified in the array in the first line of the code.
- The labels must match what is shown in the table exactly.
- The function table.moveRowAfter() is used to move each row. For more information and examples, see Making One Row Appear After Another.
- A for loop is used to iterate over the set of specified labels.
See also
- Table JavaScript and Plot JavaScript for an explanation of how to run this code.
- Table JavaScript and Plot JavaScript Reference for technical information.
- Table JavaScript and Plot JavaScript Examples Library for other examples.
- JavaScript for information about the JavaScript programming language.
- QScript for tools for automating projects using JavaScript.
- JavaScript Variables for detail on how to create new variables in the Variables and Questions tab using JavaScript.
- Making One Row Appear After Another for more examples of moving rows in tables.