1
 @products =  [#<Product id: 15, name: "abcd", revision: 100>,
              #<Product id: 19, name: "test", revision: 1080>,
              #<Product id: 5, name: "abcd", revision: 109>,
              #<Product id: 450, name: "test", revision: 9>,
              #<Product id: 2, name: "example", revision: 150>]

Question: I want to output all the products but the only condition is that if the name is duplicated more then once, then I would want to output the product which has the latest revision.

Expected Output:

@products =  [#<Product id: 19, name: "test", revision: 1080>,
              #<Product id: 5, name: "abcd", revision: 109>,
              #<Product id: 2, name: "example", revision: 150>]

As there were two products named "abcd" it should display the one with the latest revision and the same applied to "test", but as there was no duplicates for "example" it is rendered normally.

Any help will be really appreciated, have been stuck on this.

2 Answers 2

3

This should do the trick:

temp_array = @products.group_by(&:name)

@filtered_products = temp_array.map do |name, products|
  products.sort{ |p1, p2| p2.revision <=> p1.revision }.first
end

Don't hesitate to ask details if you need ;)

Sign up to request clarification or add additional context in comments.

Comments

0

ActiveRecord only:

Product.select("name, MAX(revision) AS max_revision, COUNT(*) AS count")
       .group("name")
       .having("count > 1")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.