I have an articles
array, and each of its element has source
and score
attributes. I can select the articles for each srouces[sic] with the highest score like:
articles = articles.sort_by(&:score).reverse.uniq(&:source)
What if I want to get the first three unique elements by source
? uniq
can only return the first.
Here is the desired example, you can specify uniq(first_n_element)
, to get the n elements:
# To make the example simpler,
# I use array as element
b = [["source1","10"], ["source2","9"], ["source3","8"], ["source1","7"], ["source1","9"], ["source2","8"]]
# return should contain ["source1","10"], ["source1","9"],
# because they are the first 2 distinct element by `source`,
b.sort(&:second).uniq(2) { |s| s.first }
# => [["source1","10"], ["source2","9"], ["source3","8"], ["source1","9"], ["source2","8"]]