やりたかったこと
配列内に配列があり、その配列内の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"]]
これで早くなった。
もっといい方法があれば教えてほしい。
コメントいただいてありいがとうございます!
※備忘録に近いが記載する。