Array Unique

From SwiftAPI

Jump to: navigation, search

Contents

Java

Non-order Preserving

Integer[] a = {9, 4, 0, 4, 0};
a = new HashSet<Integer>(Arrays.asList(a)).toArray(new Integer[0]);
// a == {0, 4, 9}

JavaScript

Prototype

prototype

var a = [9, 4, 0, 4, 0];
a = a.uniq();
// a == [9, 4, 0]

Perl

@a = (9, 4, 0, 4, 0);
%seen = ();
@a = grep {!$seen{$_}++} @a;
# @a == (9, 4, 0)

PHP

php.net

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
$a = array(9, 4, 0, 4, 0);
$a = array_unique($a);
# $a == array(9, 4, 0)

Python

Non-order Preserving

Note: This method will only work if all elements are hashable. Mutable objects are typically not hashable.

a = [9, 4, 0, 4, 0]
a = list(set(a))
# a == [0, 9, 4]

Order Preserving

a = [9, 4, 0, 4, 0]
b = []
for x in a:
  if x not in b:
    b.append(x)
# b == [9, 4, 0]

Ruby

uniq

Ruby-Doc.org

array.uniq => an_array
a = [9, 4, 0, 4, 0]
a = a.uniq
# a == [9, 4, 0]

uniq!

Ruby-Doc.org

array.uniq! ? array or nil
a = [9, 4, 0, 4, 0]
a.uniq!
# a == [9, 4, 0]
Personal tools