Golang : How to count duplicate items in slice/array?
Problem :
You need to count the number of duplicate items in a slice or array.
Solution :
Pseudo-code : Create a map and insert one item from the slice/array with a for loop. Before inserting a new item check if a similar item already exist in the map. If yes, increase the counter value associated with the particular item and if no, assign a new counter with the value of 1 for the new item(in the map).
Here you go :
package main
import (
"fmt"
)
func printslice(slice []string) {
fmt.Println("slice = ", slice)
}
func dup_count(list []string) map[string]int {
duplicate_frequency := make(map[string]int)
for _, item := range list {
// check if the item/element exist in the duplicate_frequency map
_, exist := duplicate_frequency[item]
if exist {
duplicate_frequency[item] += 1 // increase counter by 1 if already in the map
} else {
duplicate_frequency[item] = 1 // else start counting from 1
}
}
return duplicate_frequency
}
func main() {
duplicate := []string{"Hello", "World", "GoodBye", "World", "We", "Love", "Love", "You"}
printslice(duplicate)
dup_map := dup_count(duplicate)
//fmt.Println(dup_map)
for k, v := range dup_map {
fmt.Printf("Item : %s , Count : %d\n", k, v)
}
}
Sample output :
slice = [Hello World GoodBye World We Love Love You]
Item : You , Count : 1
Item : Hello , Count : 1
Item : World , Count : 2
Item : GoodBye , Count : 1
Item : We , Count : 1
Item : Love , Count : 2
See also : Golang : Delete duplicate items from a slice/array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+86.7k Golang : How to convert character to ASCII and back
+5.6k Get website traffic ranking with Similar Web or Alexa
+7.4k Android Studio : AlertDialog to get user attention example
+29.2k Golang : How to create new XML file ?
+31.3k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+11.8k Golang : Determine if time variables have same calendar day
+10.9k Golang : Generate random elements without repetition or duplicate
+12.6k Swift : Convert (cast) Int or int32 value to CGFloat
+9.3k Golang : Scramble and unscramble text message by randomly replacing words
+12.2k Golang : Encrypt and decrypt data with x509 crypto
+6.3k Grep : How to grep for strings inside binary data
+21.9k Golang : How to run Golang application such as web server in the background or as daemon?