【问题标题】:How can i compare 2 different arrays and delete duplicated records that already exist in second array from first array如何比较 2 个不同的数组并从第一个数组中删除第二个数组中已经存在的重复记录
【发布时间】:2020-02-01 18:04:53
【问题描述】:

我有两个不同的数组,我试图避免重复。

我尝试通过 arr1 循环而不是通过 arr2 循环,当匹配时它应该从 arr1 中删除值

def gmail_interviews 
  arr1 = []
  arr2 = []

  arr1 = [{"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
    "to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
    "snippet"=>"interview booked"},
   {"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
    "to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
    "snippet"=>"Interview booked for tomorrow"}]

  arr2 = [{"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
    "to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
    "snippet"=>"interview booked"},
   {"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
    "to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
    "snippet"=>"Interview booked for tomorrow"}]

  arr1.each_with_index do |id, index|
    if !arr2.empty?
      arr2.each_with_index do |i, ind|
        if i == id
          puts "Cant save duplicated message to db\n #{id}"
          arr1.delete_at(index)
        end   
      end 
    end
  end

  render json: arr.as_json

end 

从我的代码中,它会为 arr2 循环一次和两次 arr1 并停止而不是在两个数组中循环两次,因为它们都包含 2 个值计数

基本上它会找到 arr1[0] 的重复项,然后删除它不会循环遍历 arr1[1]

返回值应为 nil 或空,因为两个数组具有相同的值。请问我缺少什么?

【问题讨论】:

  • 最终输出想要什么,一个没有重复的数组?如果是这样,那么(arr1 + arr2).uniq

标签: ruby-on-rails arrays ruby


【解决方案1】:

怎么样

arr1 - arr2

?

例如:

arr1 = [1,2,3,4]
# => [1, 2, 3, 4]
arr2 = [2,3,10]
# => [2, 3, 10]
arr1 - arr2
# => [1, 4]

Docs

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 2017-08-08
    • 2016-12-19
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多