user2071444
user2071444

Reputation:

Sorting objects based on condition

 @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.

Upvotes: 1

Views: 38

Answers (2)

ilan berci
ilan berci

Reputation: 3881

ActiveRecord only:

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

Upvotes: 0

MrYoshiji
MrYoshiji

Reputation: 54882

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 ;)

Upvotes: 3

Related Questions