【问题标题】:Collect unique elements from array of hashes in Ruby从 Ruby 中的哈希数组中收集唯一元素
【发布时间】:2021-09-11 20:06:12
【问题描述】:

我有这些数据:

   [
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      0
   ],
   [
      {
         "identifier"=>"A",
         "inclusion"=>true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      1
   ],
   [
      {
         "identifier"=>"B",
         "inclusion"=>"true",
         "name"=>"ALK",
         "specific"=>"false"
      },
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      4
   ],
   [
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      5
   ]
]

我正在尝试根据保留已存储索引的键“标识符”提取唯一元素

我想要这样的输出

   [
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      0
   ],
   [
      {
         "identifier"=>"B",
         "inclusion"=>"true",
         "name"=>"ALK",
         "specific"=>"false"
      },
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      4
   ]
]

我尝试了几种使用 map、each_with_index 和 map_with_index 的方法,但它们没有按预期工作。

谁能帮帮我。

【问题讨论】:

  • 标识符 A 在您的输出中返回两次。目前还不清楚为什么。
  • 因为如果标识符 A 和 B 与标识符 A 相比使其唯一,这就是返回带有标识符 A 的整个数组的原因
  • 输入中的第 4 个数组由 2 个哈希组成,而其余数组仅包含一个元素
  • 能否详细说明“独特”是如何定义的?
  • “他们没有按预期工作”不是一个足够精确的错误描述,我们无法帮助您。 什么不起作用? 如何不起作用?你的代码有什么问题?您收到错误消息吗?错误信息是什么?你得到的结果不是你期望的结果吗?你期望什么结果,为什么,你得到的结果是什么,两者有什么不同?您正在观察的行为不是期望的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有何不同?

标签: arrays ruby


【解决方案1】:

我相信这里的 Ruby 专家可以大大改进它,但这里的代码应该可以满足您的需求:

  • array 是您的初始数组的名称
  • 然后我创建这个array 的副本,只保留标识符。 array2 = [["A"], ["A"], ["B", "A"], ["A"]]
  • 然后我遍历array 并检查每个元素在array2 中的第一个位置是否等于array2 中的当前位置。
array = [[{"identifier" => "A"...},0]...]

array2 = array.map { |arr| arr.map { |obj| obj.is_a?(Hash) ? obj['identifier'] : nil }.compact }

array.each_with_index.map { |arr, i| array2.index(array2[i]).eql?(i) ? arr : nil }.compact

# [[{"identifier"=>"A", "inclusion"=>"true", "name"=>"FGFR2", "specific"=>"false"}, 0], [{"identifier"=>"B", "inclusion"=>"true", "name"=>"ALK", "specific"=>"false"}, {"identifier"=>"A", "inclusion"=>"true", "name"=>"FGFR2", "specific"=>"false"}, 4]]

【讨论】:

  • 这绝对是我的工作。非常感谢。
猜你喜欢
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 2018-11-03
相关资源
最近更新 更多