arrays - 从数组中删除重复项,但根据条件保留特定的重复项
问题描述
我有一个数组[[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
可以选择在没有特殊条件的情况下再次调用。
解决方案
您可能希望将其分解为多个步骤。
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]]
推荐阅读
- c# - 具有奇怪结果的浮点数运算
- bash - Exporting awk variables to bash variables?
- c++ - 如何在编译时检查 std::span 是否具有所需的布局?
- python - 具有可变数量属性的枚举成员的 Python 元类
- php - mongodb updateOne 检查保证数据已设置
- python - 加快模式匹配并在 python 中替换大文件
- asp.net-core - Aspnetcore 身份用户对象为空
- visual-studio-code - VS Code 终端面板
- flutter - How to place image Placeholder using Image.network() in flutter?
- python - 不能完全弄清楚什么不起作用(checkio excersise "Even the Last")