Logo

Programming-Idioms

History of Idiom 119 > diff from v35 to v36

Edit summary for version 36 by programming-idioms.org:
[Go] Better demo

Version 35

2018-04-08, 22:47:11

Version 36

2018-04-11, 19:45:00

Idiom #119 Deduplicate list

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

Illustration

Idiom #119 Deduplicate list

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

Illustration
Extra Keywords
deduplicate dupe dupes redundant redundancy
Extra Keywords
deduplicate dupe dupes redundant redundancy
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
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.
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
Demo URL
https://play.golang.org/p/fBANh9c8_Ux