Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to Order an Array's Elements to Match Another Array's Element Order

by Eily (Monsignor)
on Sep 17, 2019 at 08:22 UTC ( #11106280=note: print w/replies, xml ) Need Help??

Help for this page

Select Code to Download


  1. or download this
    my %in_subset = map { $_ => 1 } @subset; # Set the value 1 for each ke
    +y in @subset
    
  2. or download this
    my @filtered = grep { exists $in_subset{$_} } @array; # grep for only 
    +the elements of @array which are in subset
    my @same = grep { $in_subset{$_} } @array; # Technically also works be
    +cause trying to access a non existing key will return undef, which is
    + false
    #Edited (missing } on the second line) thanks to AnomalousMonk
    
  3. or download this
    my %index_map = map { $array[$_] => $_  } 0..$#array; # Associate each
    + element with its index (only works for unique values though)
    my @matching_indexes = map { $index_map{$_} } @subset; # Get the index
    + for each value in @subset
    

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11106280]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2019-11-17 18:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (86 votes). Check out past polls.

    Notices?