Inc1982
Inc1982

Reputation: 1975

What is an efficient way of transforming and counting an array?

I have an array of objects that I want to count and transform. For instance:

[#<User id:1, count:0>, #<User id:2, count:0>, #<User id:2, count:0>, #<User id:3, count:0>, #<User id:1, count:0>, #<User id:1, count:0>]

would become:

[#<User id:1, count:3>, #<User id:2, count:2>, #<User id:3, count:1>]

The transformation is what confuses me, since a 'map', goes straight through, but this would be recursive.

Upvotes: 0

Views: 90

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

[user1, user2, user2, user3, user1, user1] \
  .group_by(&lambda{|x| x}) \
  .map{ |k, v| k.count = v.count; k }

Upvotes: 0

John Douthat
John Douthat

Reputation: 41179

[user1, user2, user2, user3, user1, user1].group_by(&:id).map do |id, users|
  users.first.count = users.size
  users.first
end

Upvotes: 2

Related Questions