Ruby removes duplicates from an array based on key => value

I have an array of music tracks, and in this array the same song can be displayed several times due to the release of several albums. I am trying to remove them from an array so that only true uniques is displayed in the list.

The hash looks something like this:

"tracks" => [ [0] { "id" => 1, "Title" => "Intergalactic", "ArtistName" => "Beastie Boys" }, [1] { "id" => 2, "Title" => "Intergalactic", "ArtistName" => "Beastie Boys" } ] 

I need a way to remove duplicates based on the Title key. Anyway to do this?

+7
source share
3 answers

If you use ActiveSupport, you can use uniq_by, for example:

 tracks.uniq_by {|track| track["title"]} 

If not, then you can easily implement it yourself. Watch 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 
+11
source

Array#uniq! Method Array#uniq! 1.9 takes a block, so if your hash is h , then:

 h['tracks'].uniq! { |x| x['Title'] } 

If you're in 1.8, you can fake it with:

 h['tracks'] = h['tracks'].group_by { |x| x['Title'] }.values.map(&:first) 

I assume that you want to change it in place.

+9
source

Although other methods are correct, I will add some sugar that I found elsewhere on SO.

Using this Symbol extension:

 class Symbol def with(*args, &block) ->(caller, *rest) { caller.send(self, *rest, *args, &block) } end end 

Instead of writing simple iterative blocks like

foo_array.each{ |foo| foo.update_bar("baz") } foo_array.each{ |foo| foo.update_bar("baz") } foo_array.each{ |foo| foo.update_bar("baz") } foo_array.each{ |foo| foo.update_bar("baz") } , now you can use

foo_array.each &:update_bar.with("baz")

Just as you could write maybe_nil.try(:[], "key") ...

foo_array.uniq{ |foo| foo["key"] } foo_array.uniq{ |foo| foo["key"] } foo_array.uniq{ |foo| foo["key"] } foo_array.uniq{ |foo| foo["key"] } now identical

foo_array.uniq(&:[].with("key"))

hope this helps

0
source

Source: https://habr.com/ru/post/898786/


All Articles