Created
January 30, 2014 20:30
-
-
Save wrburgess/8718091 to your computer and use it in GitHub Desktop.
Finding duplicate items in an array #ruby
This file contains 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
arr = [ 1, 2, 3, 2, 4, 5, 3] | |
My favourite way of counting elements is: | |
counts = arr.group_by{|i| i}.map{|k,v| [k, v.count] } | |
# => [[1, 1], [2, 2], [3, 2], [4, 1], [5, 1]] | |
If you need a hash instead of an array: | |
Hash[*counts.flatten] | |
# => {1=>1, 2=>2, 3=>2, 4=>1, 5=>1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment