1

I have this array of arrays:

arr =[["twitter.com", 9], ["twitter.com", 9], ["google.com", 11], ["paypal.me", 11],
      ["twitter.com", 11], ["yahoo.com", 12], ["google.com", 14], ["twitter.com", 17],
      ["twitter.com", 18], ["youtube.com", 31]]    

How can I extract the arrays that have duplicate strings and get:

[["twitter.com", 9], ["twitter.com", 9], ["google.com", 11], ["twitter.com", 11],
 ["google.com", 12], ["twitter.com", 17], ["twitter.com", 18]]    

Then add the value of the strings that are duplicate:

[["twitter.com", 64], ["google.com", 25]]    

And end up with a new array :

[["twitter.com", 64], ["youtube.com", 31], ["google.com", 25],
 ["yahoo.com", 12],["paypal.me", 11]]  

I tried:

array.select{|element| array.count(element) > 1 }   

But was getting: [["twitter.com", 9], ["twitter.com", 9]

1
  • Have you attempted the problem yourself? What did you try? Commented Nov 6, 2017 at 19:03

2 Answers 2

3

Just count all sites with each_with_object:

array.each_with_object(Hash.new(0)) {|(site, count), memo| memo[site] += count}
#=> {"twitter.com"=>64, "google.com"=>25, 
#    "paypal.me"=>11, "yahoo.com"=>12, "youtube.com"=>31}

You can simply convert the result to array by adding to_a, but IMO hash is enough for your issue.

Sign up to request clarification or add additional context in comments.

3 Comments

How would you order new array value ascendent?
@mamesaye, .sort_by {|_, v| -v}
@mamesaye: That's not idiomatic, whenever you can, use sort_by instead of sort.
2

Functional approach:

pairs.
  group_by { |k, v| k }.
  map { |k, ps| [k, ps.map { |k, v| v }.reduce(:+)] }.
  sort_by { |k, v| -v }
#=> [["twitter.com", 64], ["youtube.com", 31], ["google.com", 25],
#    ["yahoo.com", 12], ["paypal.me", 11]]

4 Comments

What do you mean by functional?
I know what community means by this term:) IMO, this code is about immutable data only.
It's all very subjective, ofc, but whenever a code uses immutable structures, modular abstractions, higher-order functions, ..., I think it may qualify as "functional". How would you write it in functional style with Ruby?

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.