Remove duplicate strings from slice. Map should containt Count. Partially done. Kindly help

I’m trying to solve a problem where I’ve been given an array of strings that will have some values repeated more than one times + values that appear only once. The task was to create a collection item that will have all the values only once. I’m trying to add a functionality where the keys of the map would be the values of the array and the value associated with the key will be the number of times the key appeared. So, I’ve go the first part sorted out:

package main

import "fmt"

func main() {
	s := []string{"one", "two", "three", "four", "four", "one", "four", "four", "five", "six", "seven", "one", "seven"}

	fmt.Printf("Original slice s:%v\n", s)
	makeMap := make(map[string]int)

	for _, value := range s {
		makeMap[value] = 0
	fmt.Printf("duplicate values removed: %v\n", makeMap)

Here’s the output:

pritesh@debian:~/go/src/$ go run main.go 
Original slice s:[one two three four four one four four five six seven one seven]
duplicate values removed: map[five:0 four:0 one:0 seven:0 six:0 three:0 two:0]

I am unable to add the funcationality where I can add the count.
I tried this:

 	for _, value := range s {
		counter := 0
		if _, ok := makeMap[value]; ok {
		makeMap[value] = counter

But this doesn’t work, which makes sense, because, a map can contain only 1 value, so the moment it sees another value coming in, it deletes the previous one and “overwrites” it.

I then tried putting another for key, _ := range makeMap and inside that I tried to see if the key appears again, but since this loop is in the first loop, I get wrong values.
So, how do I go about getting the count right? Or I am trying something that is fundamentally not possible with the approach I am taking to solve the problem?


Add a function that returns the number of times a item is found in the slice

func count(s []string, item string) int {
   count := 0
   for _, value := range s {
      if value == item {
   return count

And to fill the ■■■■ in your map,

for _, value := range s {
		makeMap[value] = count(s, value)

And now your only need to take those items which count value is 1.

func removeDuplicates(m map[string]int, s []string) []string {
   result := make([]string, 0)

   for key, value := range m {
      if value == 1 {
         result = append(result, key)
   return result



Hi Yamil,
Thank you. There’s so much I learn from your answers.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.