【发布时间】:2022-01-22 21:44:51
【问题描述】:
我正在尝试找出一种有效的方法来从字符串数组中删除重复项,但不是在单个数组中,而是从所有数组中。
很难解释,所以我举个例子:
[
["Word1", "Word2", "Word3", "Word4"],
["Word1", "Word5", "Word3", "Word4"],
["Word1", "Word2", "Word3", "Word7"],
]
预期结果:
[
["Word2", "Word4"],
["Word5", "Word4"],
["Word2", "Word7"],
]
索引 0:已删除,因为所有索引 0 都是相同的。
索引 1:保留,因为并非所有索引 1 都是相同的。 等等……
我离得越近
def clean_duplicates(attributes)
valid_attributes = attributes.map { [] }
attributes.first.count.times.each do |i|
next if attributes.all? { |v_attrs| v_attrs[i] == attributes.last[i] }
attributes.each_with_index do |_, v|
valid_attributes[v].push(attributes[v][i])
end
end
valid_attributes
end
clean_attributes([["Word1", "Word2", "Word3", "Word4"], ["Word1", "Word5", "Word3", "Word4"], ["Word1", "Word2", "Word3", "Word7"]])
=> [["Word2", "Word4"], ["Word5", "Word4"], ["Word2", "Word7"]]
有没有更好的办法?
谢谢!
【问题讨论】:
标签: arrays ruby-on-rails ruby