ruby on rails - 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: want output products condition if name duplicated more once, want output product has 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 2 products named "abcd" should display 1 latest revision , same applied "test", there no duplicates "example" rendered normally.

any appreciated, have been stuck on this.

this should trick:

temp_array = @products.group_by(&:name)  @filtered_products = temp_array.map |name, products|   products.sort{ |p1, p2| p2.revision <=> p1.revision }.first end 

don't hesitate ask details if need ;)


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -