In some cases you may want to use a specific ordering of brands or statements in the rows of a table, and it may not be efficient to modify the Variable Sets (for example, if you have tens or hundreds of Variable Sets to order). The Table JavaScript code below specifies the order in which the rows on a table should appear, and can be used in a custom rule.
Technical detail
You provide a list of row labels in the order you'd like them to be. If any are not found in the table, a warning will be returned. Otherwise, the rows will be reordered as specified. Keep in mind that if your table has more than the rows specified, those remaining rows will be at the bottom. Note if you'd like to use this on columns rather than rows, change "Row" to "Column" in the code below (keep capitalization as it is in code).
Method
//Specify row order using row labels
var row_order = ["Pepsi ", "Coca Cola ", "NET Sugarred", "Pepsi Light ", "Pepsi Max", "Diet Coke", "Coke Zero", "NET Sugarless", "NET"]; //pull of row labels on table to compare
var row_labels = table.rowLabels;
//If any of the specified rows aren't present a warning will be returned var not_found_labels = row_order.filter(function (label) { return row_labels.indexOf(label) == -1; }) if (not_found_labels.length > 0) { log("Could not find labels in the rows of the table:\r\n" + not_found_labels.join("\r\n")); //else the rows will be reordered
} else {
//create empty variable last to hold previous label that was moved var last;
//loop through each label specified and move the next one after the previous row_order.forEach(function (label, ind) { //if the first time through the loop, the row will be moved to top (null)
if (ind == 0) { table.moveRowAfter(table.rowIndex(label), null);
//else the row will be moved after the previous label's row } else { table.moveRowAfter(table.rowIndex(label), table.rowIndex(last)); }
//change the last previous label to current label for next iteration last = label; }); }
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.