Making One Row Appear After Another

From Q
Jump to: navigation, search

This example uses JavaScript to move one a row in a table. It moves a row called 'Coke' to be after the row called 'Pepsi'. It is the programming way to achieve the same result as dragging and dropping on the Outputs Tab.

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.

table.moveRowAfter(table.rowIndex('Coke'), table.rowIndex('Pepsi'));

Note that:

  • table.rowIndex('Coke') finds the row number in the table with the label of Coke.
  • If Coke is in the first row of the table (excluding the headers), a value of 0 is returned by table.rowIndex('Coke'). If it is in the second row, a value of 1 is returned, and so on. This gets a bit of getting used to, but it is a standard convention in programming, because it makes more advanced computations simpler. This convention is used throughout JavaScript.
  • The code looks up the position of the Coke row and the Pepsi row and then instructs Q to rearrange the table so that the Coke row appears after the Pepsi row. That is, the rowIndex code works out the numbers of the rows and the instructions are given to Q in terms of row numbers.
  • moveRowAfter and rowIndex are functions written for use in Q and are documented in.
  • This code will only work if the table contains rows called Coke and Pepsi. If the tables does not contain these rows an error will be returned:
There is an error in your JavaScript
There is no row at index -1.

These entries were logged:
error: There is no row at index -1.  on line 1 (column 6).
The cause of this error is that table.rowIndex('Coke') and table.rowIndex('Pepsi') return values of -1 when these text strings cannot be found. That that the bottom line of the error message identifies that the precise location where the error was encounted (line 1, column 6). A better bit of code which avoids the possibility of this error is:
var coke_row = table.rowIndex('Coke');
var pepsi_row = table.rowIndex('Pepsi');
if (coke_row != -1 && pepsi_row != -1)
	table.moveRowAfter(coke_row, pepsi_row);
Note that:
  • var coke_row = table.rowIndex('Coke'); is creating a new variable called coke_row storing the row index.
  • != means not equal to (see Relational operators.
  • && means and (see Logical operators.
  • An if statement is being used so that the row is only moved in situations where the movement makes sense.

See also