in reply to Re^2: Sort array + keep associated indexes in other array
in thread Sort array + keep associated indexes in other array
In that case, you can zip the arrays together before sorting them, then unzip them afterwards.
Something like...
use Data::Dumper; my @array_items = ("dog" ,"desk" ,"cow"); my @array_items_weight = ("20" ,"10", "150"); # zip them together my @combined = map { [$array_items[$_], $array_items_weight[$_]] } 0 .. $#array_items; # sort the zipped array my @sorted = sort { $a->[0] cmp $b->[0] } @combined; # unzip again @array_items = map { $_->[0] } @sorted; @array_items_weight = map { $_->[1] } @sorted; print "\@array_items is now... "; print Dumper \@array_items; print "\@array_items_weight is now... "; print Dumper \@array_items_weight;
The above produces the following output...
@array_items is now... $VAR1 = [
'cow',
'desk',
'dog'
];
@array_items_weight is now... $VAR1 = [
'150',
'10',
'20'
];
This solution assumes that @array_items and @array_items_weight are equal in length.
Zipping them together is somewhat ugly code, but with the assistance of List::MoreUtils it can be made more beautiful:
my @combined = pairwise { [$a, $b] } @array_items, @array_items_weight +;
|
|---|