Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 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 Reply

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...