Iterators · Each-Left · Practice Question
Sort Multiple Lists Together by a Key Row
Question
Given:
d:(5 3 1 2 4;`s`t`y`a`i)Reorder both rows together, so that the first row is sorted ascending.
Expected result:
1 2 3 4 5
`y`a`t`i`sSolution
d@\:iasc d[0]Explanation
iasc d[0]returns the indexes that would sort the first row ascending — not the sorted values themselves, but the order needed to get there:
q)iasc d[0]
2 3 1 4 0The each-left iterator:
\:then pairs that fixed index list against every row of d in turn, indexing each row independently with the same index order:
d[0]@2 3 1 4 0 / 1 2 3 4 5
d[1]@2 3 1 4 0 / `y`a`t`i`sBecause both rows are indexed with the same index list, they stay aligned with each other — the symbol that was paired with 5 (the largest number) is still paired with it after sorting, just relocated to the end. This pattern is how parallel rows or columns are kept in sync in q without sorting them separately.