0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby 配列で重複した項目のみを取り出す

Last updated at Posted at 2022-01-06
arr = [1, 2, 3, 2, 4, 1, 5, 5]

arr.tally.filter_map { |k, v| k if v > 1 }.sort
=> [1, 2, 5]

arr.group_by{ |i| i }.reject{ |k,v| v.one? }.keys.sort
=> [1, 2, 5]

arr.filter_map{ |i| i if arr.count(i) > 1 }.uniq.sort
=> [1, 2, 5]

※2022/01/10追記
@jnchito さん から Enumerable#tally を使う方法をご提案いただきました。
https://qiita.com/akinov/items/3dad33174eb9e0c91f39#comment-075b6b4a1a80b624d417

0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?