0
0

More than 5 years have passed since last update.

【Ruby】配列内の配列のkeyをで重複をなくす方法

Last updated at Posted at 2019-05-03
1 / 6

やりたかったこと

配列内に配列があり、その配列内の1要素をkeyとして重複を消したい。


環境

ruby 2.5.1p57 (2018-03-29 revision 63029)

sandbox.rb

sandbox.rb
def test()
  array = [["id01",111,"1"],["id01",222,"2"],["id02",111,"1"],["id02",222,"2"],["id01",333,"3"]]
  p array.group_by{ |e| e.first }.select { |k, v| v}.map{|m| m.last.last}
end
test()

内容

Ruby: 配列で重複してるものを探す - 宇宙船サンドボックスを参考に記述を変更した。
業務上1億件近くのデータを扱うため速度は重要だった。
配列で重複した場合は後勝ちとした。


結果

これが
[["id01", 111, "1"], ["id01", 222, "2"], ["id03", 111, "1"], ["id02", 111, "1"], ["id02", 222, "2"], ["id01", 333, "3"]]
これに
[["id01", 333, "3"], ["id02", 222, "2"], ["id03", 111, "1"]]

これで早くなった。
もっといい方法があれば教えてほしい。
コメントいただいてありいがとうございます!

※備忘録に近いが記載する。

0
0
2

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