Category: >> Perl Code >> Removing duplicate array items while preserving order Bookmark and Share

<< lastnext >>

Snippet Name: Removing duplicate array items while preserving order

Description: This snippet removes duplicate array items while preserving the array order.
Each string is tested to see if that key already refers to a non-false value. The post-increment operator (++) adds one to that key's value, but only after the condition is checked. The result is that the first time a key string is encountered the condition is false (since the value is undefined) and the key is therefore pushed onto the second array.

Also see:
» Remove empty lines from a string o...
» Add and Remove classes in Javascri...
» Remove empty lines from text files
» Randomize an array
» Get every 2nd (or 3rd, 4th, ...) e...
» Grab the last element of an array
» Create an array from the contents ...
» Create an array from comma separat...
» Remove Duplicate Lines from a File
» Dynamically add and remove elements
» Remove Extra Spaces From A String
» Dynamically Add/Remove rows in HTM...
» ORDER BY Clause
» Check for duplicates and delete du...
» Remove Duplicate Lines from a File
» Find all duplicates in a column
» Remove all non-ASCII chars
» Get ordered list of near match ite...
» Remove Duplicates
» Remove extra linebreaks
» Add/Remove from Select list
» Eliminate duplicate records
» Set/Get/Remove Cookies
» Remove All Files An A Given Direct...
» Find All Duplicate Rows

Comment: (none)

Author: CoderZone
Language: PERL
Highlight Mode: PERL
Last Modified: December 03rd, 2010

@arr = qw(one two one three four two four);
foreach (@arr) {
    push(@arr2, $_) unless ($seen{$_}++);
print "@arr2";
# returns 'one two three four'
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© | users online: 27