This article describes how to change the order of rows or columns in a table...
... based on a specified order:
Requirements
Please note these steps require a Displayr license.
- A table with rows and/or columns.
- You have read How to Create a Custom Rule and How to Modify Table Rows and Columns Using a Rule.
Method
1. Select your table.
2. From the object inspector, go to Data > Rules.
3. Click the Plus (+) button.
4. Click New custom rule (write your own JavaScript) > Edit JavaScript.
5. Paste the below into the dialog:
form.setHeading("Custom sorting");
form.setSummary("Custom sorting");
var labels = ['Pepsi Max','Coke Zero','Diet Pepsi','Diet Coke','Pepsi','Coke'];
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]);
}
- The first 2 lines set the name of the rule that appears in the object inspector and the dialog window.
- We then set the order of the labels by specifying them in an array called
labels
. Only specify labels that match those in your table exactly. Any others not listed will be left at the end. - The main part of the code is kept in a
for..loop
to run through each label inlabels
. - Here, we are sorting the table rows so we use the
table.moveRowAfter
function which requires the index of the row to be moved and its new position. -
table.rowIndex
finds the label in the row and returns its position. -
last_index
gets updated with the correct position based on the new order.
6. OPTIONAL: To apply this script to columns instead, you would adjust the code within the loop as follows:
table.moveColumnAfter(table.columnIndex(labels[i]), last_index);
last_index = table.columnIndex(labels[i]);
7. Press the blue Play button > OK > OK.