arrayssortingrakuindices

Best ways to sort array of arrays?


I need to sort an array of arrays; the .sort method seems to work by default. But what is a good way to sort by different indices of the inner arrays?

The array to be sorted is outer larger array: (birthday in 'mmddyy' format)

my @allRecords = [ [birthday1 firstName1 lastName1 [data1]
                   [birthday2 firstName2 lastName2 [data2] 
                   ...
                   [birthdayN firstNameN lastNameN [dataN] ];

@allRecords.sort by itself sorts by birthdays. 

What is a better way to sort by firstName or lastName or by data inside the inner arrays?


Solution

  • The sort method takes a sub as optional argument. If its arity is 1, it uses the return value as comparison operands; if its arity is 2, you can manually do the comparison between elements however you see fit by returning one of Less, Same or More.

    Given your example, we can sort by first name like this:

    @allRecords.sort(*.[1]);
    

    We can sort by last name, then first name, then birthday by doing the separate comparisons explicitly like this:

    @allRecords.sort(-> $a, $b {
        $a[2] cmp $b[2] || $a[1] cmp $b[1] || $a[0] cmp $b[0]
    });
    

    or again implicitly by transforming the operands:

    @allRecords.sort(*.[2...0]);
    

    Transforming the birthday entry so we sort by year first is left as an exercise for the reader, but one way to do it would be to add something like

    .comb(2).list.rotate(-1).join
    

    where appropriate.