icon Top 9 categories map      RocketAware > Perl >

How can I extract just the unique elements of an array?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.


Search Perl pages


By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Integer, Floating point, Matrix, Statistics, Boolean, ...

Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...


How can I extract just the unique elements of an array?

There are several possible ways, depending on whether the array is ordered and whether you wish to preserve the ordering.

a) If @in is sorted, and you want @out to be sorted:
    $prev = 'nonesuch';
    @out = grep($_ ne $prev && ($prev = $_), @in);

This is nice in that it doesn't use much extra memory, simulating uniq(1)'s behavior of removing only adjacent duplicates.

b) If you don't know whether @in is sorted:
    undef %saw;
    @out = grep(!$saw{$_}++, @in);

c) Like (b), but @in contains only small integers:
    @out = grep(!$saw[$_]++, @in);

d) A way to do (b) without any loops or greps:
    undef %saw;
    @saw{@in} = ();
    @out = sort keys %saw;  # remove sort if undesired

e) Like (d), but @in contains only small positive integers:
    undef @ary;
    @ary[@in] = @in;
    @out = @ary;

Source: Perl FAQ: Data Manipulation
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How can I tell whether an array contains a certain element?

Previous: What is the difference between $array[1] and @array[1]?

(Corrections, notes, and links courtesy of RocketAware.com)

[Overview Topics]

Up to: Data structures (In memory)

Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq4/How_can_I_extract_just_the_uniqu.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments