0

私は単純な配列を持っています:

[
    [0] {
        "user_id" => 4,
           "type" => 1
    },
    [1] {
        "user_id" => 4,
           "type" => 1
    },
    [2] {
        "user_id" => 1,
           "type" => 1
    },
    [3] {
        "user_id" => 2,
           "type" => 65
    },
    [4] {
        "user_id" => 1,
           "type" => 23
    },
    [5] {
        "user_id" => 4,
           "type" => 4
    }
]

私がやりたいのは、同じ user_id と type を持つ要素を削除してから、それらを組み合わせて配列として戻すことだけです。したがって、この場合の結果は次のようになります。

[
    [0] {
        "user_id" => 1,
           "type" => 1
    },
    [1] {
        "user_id" => 2,
           "type" => 65
    },
    [2] {
        "user_id" => 1,
           "type" => 23
    },
    [3] {
        "user_id" => 4,
           "type" => 4
    },
    [4] [
        [0] {
            "user_id" => 4,
               "type" => 1
        },
        [1] {
            "user_id" => 4,
               "type" => 1
        }
    ]
]

これを行う簡単な方法はありますか、それとも手動で反復して実行する必要がありますか? ありがとう

4

1 に答える 1

2
require 'pp'
a = [
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 1,
           "type" => 1
    },
    {
        "user_id" => 2,
           "type" => 65
    },
    {
        "user_id" => 1,
           "type" => 23
    },
    {
        "user_id" => 4,
           "type" => 4
    }
]

pp a.group_by{|i| i.values_at("user_id","type") }.values

output:

[[{"user_id"=>4, "type"=>1}, {"user_id"=>4, "type"=>1}],
 [{"user_id"=>1, "type"=>1}],
 [{"user_id"=>2, "type"=>65}],
 [{"user_id"=>1, "type"=>23}],
 [{"user_id"=>4, "type"=>4}]]

アップデート

require 'pp'
a = [
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 1,
           "type" => 1
    },
    {
        "user_id" => 2,
           "type" => 65
    },
    {
        "user_id" => 1,
           "type" => 23
    },
    {
        "user_id" => 4,
           "type" => 4
    }
]

arr = a.map do |i|
  tot = a.count(i)
  next ([i] * tot) if tot > 1 ; i
end.uniq
pp arr

出力:

[[{"user_id"=>4, "type"=>1}, {"user_id"=>4, "type"=>1}],
 {"user_id"=>1, "type"=>1},
 {"user_id"=>2, "type"=>65},
 {"user_id"=>1, "type"=>23},
 {"user_id"=>4, "type"=>4}]
于 2013-07-02T12:25:45.240 に答える