Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

ruby on rails - In group_by, if different array array havingsame 'nil' element then it considering only one, but i want all of them

status_json = [
  {
    "enquiries_ids"=>[65219, 65210, 65194], 
    "ncds"=>[nil, nil, "2020-05-31"], 
    "broker_id"=>256, 
    "status_id"=>49, 
    "visit_date"=>nil
  }, 
  {
    "enquiries_ids"=>[65220, 65221], 
    "ncds"=>[nil, nil], 
    "broker_id"=>351, 
    "status_id"=>49, 
    "visit_date"=>nil
  }, 
  {
    "enquiries_ids"=>[65227], 
    "ncds"=>[nil], 
    "broker_id"=>403, 
    "status_id"=>49,
    "visit_date"=>Date.new(2020, 5, 20)
  }, 
  {
    "enquiries_ids"=>[65228], 
    "ncds"=>[nil], 
    "broker_id"=>449,
    "status_id"=>49, 
    "visit_date"=>nil
  }, 
  {
    "enquiries_ids"=>[65218, 65217], 
    "ncds"=>[nil, nil], 
    "broker_id"=>599, 
    "status_id"=>49, 
    "visit_date"=>nil
  }
]
bk = status_json.group_by { |h| h["ncds"] }.map { |k,v| [k] }.flatten!

It returning

[nil, nil, "2020-05-31", nil, nil, nil]

But actualy it want

[nil, nil, "2020-05-31", nil, nil, nil, nil, nil, nil]

How we will do this, Thanks in advance.

question from:https://stackoverflow.com/questions/66060710/in-group-by-if-different-array-array-havingsame-nil-element-then-it-consideri

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you group it status_json.group_by { |h| h["ncds"] } you get a hash with three keys, because it's what group_by does:

{
  [nil, nil, "2020-05-31"]=>[
    {"enquiries_ids"=>[65219, 65210, 65194], "ncds"=>[nil, nil, "2020-05-31"], "broker_id"=>256, "status_id"=>49, "visit_date"=>nil}
  ],
  [nil, nil]=>[
    {"enquiries_ids"=>[65220, 65221], "ncds"=>[nil, nil], "broker_id"=>351, "status_id"=>49, "visit_date"=>nil},
    {"enquiries_ids"=>[65218, 65217], "ncds"=>[nil, nil], "broker_id"=>599, "status_id"=>49, "visit_date"=>nil}
  ],
  [nil]=>[
    {"enquiries_ids"=>[65227], "ncds"=>[nil], "broker_id"=>403, "status_id"=>49, "visit_date"=>#<Date: 2020-05-20>},
    {"enquiries_ids"=>[65228], "ncds"=>[nil], "broker_id"=>449, "status_id"=>49, "visit_date"=>nil}
  ]
}

To collect all arrays in a new one you can iterate through status_json using flat_map:

bk = status_json.flat_map { |h| h["ncds"] }

Which gives you:

[nil, nil, "2020-05-31", nil, nil, nil, nil, nil, nil]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...