Here’s the problem. I have a list of ‘things’, for example, batch names. I can also get another list, for example, the start dates of the batches. How do I sort the batches by date? The answer: use the Rank Index function.
I have two lists: lstBatches and lstStartDates. The two lists share a common index i.e. lstStartDates[i] is the start date for the i’th batch identified by lstBatches[i];
I want to sort the items in lstBatches in ascending order of start date. The Rank Index function will give me a vector of indices that correspond to the items of the list once sorted into ascending order:
ri = Rank Index(lstStartDates)
Note it doesn’t actually sort the list, but it tells me the order of the items if they were sorted. I can now apply this ordering to my list of batches:
1 2 |
ri = Rank Index(lstStartDates); lstBatchesByDate = lstBatches[ri]; |
Sorted!
A word of caution. If you have a list with a single element e.g. lstBatches= {“test”} then the Rank Index will generate a scalar variable: lstBatchesByDate = “test”. That makes sense if you think about it but if you don’t account for this possibility then you might get caught out when using list-specific functions such as NItems.