Sorting errors by unique attributes

Working with the following code, I only need to return records where the `point 'attribute is unique. I can't seem to get there.

uniques = Item.find_all_by_item_id(item_id)
uniques.sort! {|a, b| b.point <=> a.point } # how do I reject the equal points?

      

In other words, I suppose, how do you do [0, 1, 1, 1, 2, 3, 3, 4, 4, 7] # => [0, 2, 7]?
0


source to share


2 answers


How about this:



# Get the number of items with each point value
counts = Item.count("point", :group => "point")

# Get the IDs of all entries that only show up once
unique_ids = counts.collect { |count| count[0] if count[1] == 1 }.compact

unique_items = Item.find_all_by_id(unique_ids)

      

+1


source


I can think of several ways in my head to do this:

uniques.reject!{|u| uniques.select{|x| x == u}.size > 1}

      

Basically, iterate through the uniques array and then see if the array has more than one of these elements. Obviously there are many clever ways to speed up this, but for small arrays this should work.



or

h = Hash.new(0)
uniques.each{|u| h[u] += 1}
h.reject{|k,v| v > 1}.keys

      

Basically count how many times each item appears in the hash if more than one is rejected and then just looking at the keys.

+1


source







All Articles