Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a Count of Array Items that Meet a Certain Criteria

I have an array called @friend_comparisons which is populated with a number of user objects. I then sort the array using the following:

@friend_comparisons.sort! { |a,b| b.completions.where(:list_id => @list.id).first.counter <=> a.completions.where(:list_id => @list.id).first.counter }

This is sorting the array by a certain counter associated with each user (the specifics of which are not important to the question).

I want to find out how many user objects in the array have a counter that is greater than a certain number (let's say 5). How do I do this?

Here is how I am currently solving the problem:

@friends_rank = 1
for friend in @friend_comparisons do
  if friend.completions.where(:list_id => @list.id).first.counter > @user_restaurants.count
    @friends_rank = @friends_rank + 1
  end
end
like image 677
Alex Avatar asked May 30 '12 21:05

Alex


People also ask

How do you count elements in an array with conditions?

To count the elements in an array that match a condition: Use the filter() method to iterate over the array. On each iteration, check if the condition is met. Access the length property on the array to get the number of elements that match the condition.

How do you count the number of items in an array?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do I count a list of conditions in Python?

Use len() & List comprehension to count elements in list based on conditions. We can use list comprehension to create a new list of elements that satisfies our given condition and then get the length of this new list to find out number of elements in original list that satisfies our condition i.e.


2 Answers

You can use Array#count directly.

@friend_comparisons.count {|friend| friend.counter >= 5 }

Docs: http://ruby-doc.org/core-2.2.0/Array.html#method-i-count

(same for ruby 1.9.3)

like image 112
borod108 Avatar answered Oct 13 '22 01:10

borod108


Array#select will get the job done.

Docs: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select

You might do something like this:

number_of_users = @friend_comparisons.select{|friend| friend.counter >= 5 }.size
like image 28
MrTheWalrus Avatar answered Oct 13 '22 00:10

MrTheWalrus