Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Hash Multiple values for a key-Filtering unique values for a key in hash

by kcott (Archbishop)
on May 23, 2017 at 05:59 UTC ( [id://1190930]=note: print w/replies, xml ) Need Help??


in reply to Hash Multiple values for a key-Filtering unique values for a key in hash

G'day rahulme81,

That's a FAQ: How can I remove duplicate elements from a list or array?.

To keep the values unique for a specific key, without removing duplicates from the values of other keys, you'll need to clear the %seen hash for each arrayref value. Here's how you might implement that:

#!/usr/bin/env perl use strict; use warnings; use Data::Dump; my $HASH1 = { 'Alabama' => ['Andalusia', 'Anniston', 'Clanton', 'Eufaula', 'Auburn', + 'Bessemer', 'Eufaula', 'Auburn', 'Bessemer' ], 'California' => ['Barstow','Barstow'], 'Georgia' => ['Darien'], 'New York' => ['Amsterdam','Coney Island','Coney Island','Beacon','Bec +on'] }; for (values %$HASH1) { my %seen; $_ = [ grep { ! $seen{$_}++ } @$_ ]; } dd $HASH1;

Output:

{ "Alabama" => [ "Andalusia", "Anniston", "Clanton", "Eufaula", "Auburn", "Bessemer", ], "California" => ["Barstow"], "Georgia" => ["Darien"], "New York" => ["Amsterdam", "Coney Island", "Beacon", "Becon"], }

Note that the input shown in your OP has the two unique values 'Beacon' and 'Becon', but your expected output only has 'Becon': I suspect a typo. Beyond that, my actual output matches your expected output.

See also: values.

— Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-24 10:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found