Created
October 3, 2017 15:00
-
-
Save arehmandev/4790544bf08f9965596eb0d75f9f270b to your computer and use it in GitHub Desktop.
Remove duplicates in a slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func removeDuplicates(elements []string) []string { // change string to int here if required | |
| // Use map to record duplicates as we find them. | |
| encountered := map[string]bool{} // change string to int here if required | |
| result := []string{} // change string to int here if required | |
| for v := range elements { | |
| if encountered[elements[v]] == true { | |
| // Do not add duplicate. | |
| } else { | |
| // Record this element as an encountered element. | |
| encountered[elements[v]] = true | |
| // Append to result slice. | |
| result = append(result, elements[v]) | |
| } | |
| } | |
| // Return the new slice. | |
| return result | |
| } | |
| // usage: removeDuplicates(slice) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.