Ruby removing duplicates from array based on key=>value
If you are using ActiveSupport, you can use uniq_by, like so :
tracks.uniq_by {|track| track["title"]}
If not, then you can easily implement it yourself. See this.
# File activesupport/lib/active_support/core_ext/array/uniq_by.rb, line 6
def uniq_by
hash, array = {}, []
each { |i| hash[yield(i)] ||= (array << i) }
array
end
The Array#uniq!
method in 1.9 takes a block so if your Hash is h
then:
h['tracks'].uniq! { |x| x['Title'] }
If you're in 1.8 then you can fake it with:
h['tracks'] = h['tracks'].group_by { |x| x['Title'] }.values.map(&:first)
I'm assuming that you want to modify it in-place.