首页 > 解决方案 > 从数组中删除重复项,但根据条件保留特定的重复项

问题描述

我有一个数组[[1, nil, nil], [1, 123, nil]],我要求uniq根据第一个值删除重复项。nil但是我想专门保留第二个值没有的副本(123在这种情况下)

my_array.uniq { |arr| arr.first.id }

可能会返回[[1, nil, nil]],但我想确保它返回[[1, 123, nil]]。有什么办法可以用这种rails风格来做uniq吗?

正如下面 thinkgruen 所说,我不太关心有 3 个重复项的情况,因为uniq可以选择在没有特殊条件的情况下再次调用。

标签: arraysruby-on-railsruby

解决方案


您可能希望将其分解为多个步骤。

my_array = [[1, nil, nil], [1, 123, nil]]

# Group them
grouped = my_array.group_by(&:first)

# Decide which to keep
grouped.values.map do |group|
  # Detect one where the 2nd value isn't nil.  Otherwise take the first.
  group.detect { |object| !object[1].nil? } || group.first
end

 => [[1, 123, nil]]

推荐阅读