在Ruby中通过过滤从数组中删除重复的数组项

时间:2018-07-02 10:42:41

标签: ruby

我有一系列物品:

[
  ["20180629", "14:49", "google", "iOS", "Safari", "1"], 
  ["20180629", "12:22", "google", "Android", "Chrome", "2"],
  ["20180629", "17:20", "google", "iOS", "Safari", "1"], 
  ["20180629", "16:30", "(direct)", "iOS", "Safari", "1"], 
  ["20180629", "09:29", "(direct)", "Android", "Chrome", "2"]
]

除了前两个(时间码)之外,我需要删除具有所有相同项目的重复子数组。我将代码范围缩小到了这个范围:

exclude_from_filter = [0,1]


array.each_with_index.map do |array, index|
  array.reject.with_index { |e,i| exclude_from_filter.include? i }
end.uniq!

删除时间码,然后删除重复的项目:

[
  ["google", "iOS", "Safari", "1"], 
  ["google", "Android", "Chrome", "2"], 
  ["(direct)", "iOS", "Safari", "1"], 
  ["(direct)", "Android", "Chrome", "2"]
]

但是我想摆脱重复的项目,而保留一个唯一值不变:

[
  ["20180629", "14:49", "google", "iOS", "Safari", "1"], 
  ["20180629", "12:22", "google", "Android", "Chrome", "2"],
  ["20180629", "16:30", "(direct)", "iOS", "Safari", "1"], 
  ["20180629", "09:29", "(direct)", "Android", "Chrome", "2"]
]

这是我完全迷路的地方

1 个答案:

答案 0 :(得分:3)

如果您只想基于最后4个值删除重复项,请在块中使用uniq

ary.uniq { |e| e[2..5] }
 => [["20180629", "14:49", "google", "iOS", "Safari", "1"],
     ["20180629", "12:22", "google", "Android", "Chrome", "2"],
     ["20180629", "16:30", "(direct)", "iOS", "Safari", "1"],
     ["20180629", "09:29", "(direct)", "Android", "Chrome", "2"]] 

或者,要基于除前两个以​​外的所有值删除它们,请执行以下操作:

ary.uniq { |e| e[2..-1] }

也可以写成(塞尔吉奥的建议):

ary.uniq { |date, time, *rest| rest }