Logo

Programming-Idioms

History of Idiom 119 > diff from v5 to v6

Edit summary for version 6 by :
New Go implementation by user [programming-idioms.org]

Version 5

2016-01-15, 12:51:41

Version 6

2016-01-15, 12:57:36

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Code
y := make(map[T]struct{}, len(x))
for _, v := range x {
	y[v] = struct{}{}
}
x2 := make([]T, 0, len(y))
for _, v := range x {
	if _, ok := y[v]; ok {
		x2 = append(x2, v)
		delete(y, v)
	}
}
x = x2
Comments bubble
T is the type of the items.
Iterate twice, from list to map, then from map to list.
Original order is preserved.
Demo URL
http://play.golang.org/p/1f4D_TkAwC