Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #240 Sort 2 lists together

Lists a and b have the same length. Apply the same permutation to a and b to have them sorted based on the values of a.

use List::Util qw(zip pairmap unpairs);
@keys = qw(x y a f e n);
@vals = qw(1 2 3 4 5 6);

pairmap { push @new_keys, $a; push @new_vals, $b }
    unpairs 
        sort { $a->[0] cmp $b->[0] } 
            zip \@keys, \@vals;

zip interleaves the two lists into a list of list-pairs. These are sorted using the 0th element of each pair (corresponding to the keys). The list of pairs is flattened by unpairs. Finally, pairmap iterates over the flattened list of pairs and pushes the $a and $b (first and second) element of each pair onto new lists.
(->> (map vector a b)
     (sort-by first)
     (apply (partial mapv vector)))

this returns [a b]
the last line is from the 2d- transpose solution

New implementation...
< >
programming-idioms.org