0

Controller:

@user_location = Country.joins(:user).order(:name).compact.uniq

View (haml):

- @user_location.each do |user|
  %li= user.name

At this point, all duplicate elements of the array are deleted (uniq).

How can I display the number of repetitive elements in the array? For example: if my array has

One Two Two Three Four

then I need to show

One Two (2) Three Four

2
  • This seems like a simple algorithm question. Have you made any attempts yet? Commented Mar 2, 2018 at 15:19
  • What's a repetitive element? Commented Mar 2, 2018 at 16:55

4 Answers 4

3

I would expect that something like this might work:

# in the controller (this returns a hash)
@locations = Country.joins(:user).order(:name).group(:name).count

# in your view
- @locations.each do |name, count|
  %li
    = name
    = "(#{count})" if count > 1
Sign up to request clarification or add additional context in comments.

Comments

2

You need group_by + map. Like this:

array.group_by(&:itself).map do |k, v|
 { value: k, count: v.length }
end

You will have array of hashes like this: {value: 'Two', count: 2}.

You can return data in any desired way. However, it's much better to get grouped records directly from SQL.

4 Comments

Oo very nice: +1
You might want to replace group_by{ |x| x} with group_by(&:itself) to improve readability
I was wondering what that shorthand looked like @spickermann. Thanks for the comment.
You could even directly map the output as v > 1 ? "#{k} (#{v})" : k.
1

You can iterate through using each_with_object, counting elements as they're assigned to a hash key. For example:

array = %w(One Two Two Three Four)

counts = array.each_with_object(Hash.new(0)) do |el, hash| 
  hash[el] += 1
end
# => {"One"=>1, "Two"=>2, "Three"=>1, "Four"=>1}

counts.map { |k, v| v > 1 ? "#{k} (#{v})" : k }
# => ["One", "Two (2)", "Three", "Four"]

Does that look like what you're after? If not, or you've any questions, let me know!

Comments

0
%w[One Two Two Three Four].
  group_by{|x|x}.
  map{|k, v|[k,v.count>1?" (#{v.count})":nil]}.
  map(&:compact).
  map(&:join)
#⇒ ["One", "Two (2)", "Three", "Four"]

2 Comments

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
@RosárioPereiraFernandes feel free to edit this answer as you wish. I am positive it’s self-explanatory for any future reader who has a base understanding of ruby syntax.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.