从嵌套数组中删除重复项 [英] Remove duplicates from nested array

查看:143
本文介绍了从嵌套数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组数组,其中包含一个特定顺序的数字。我想删除嵌套数组中的重复项,但是有一个层次结构:如果一个数字出现在数组的较低索引中,则将数组链中的所有副本都删除。


$ b $例如:
nums = [[10,6,14],[6],[10,6,9],[10,13,6],[10,13,6,9, 16],[10,13]]



nums [0]包含[10,6,14],所以随后提及的10,6,14应该从链中的其他数组,意思是nums [2]应该有10,6个删除,只有9个应该保留。



我无法使用嵌套循环,任何Ruby向导都可以帮助吗?

解决方案

应该这样做:

  input = [[10,6,14],[6],[10,6,9],[10,13,6],[10,13,6,9 ,16],[10,13]] 
seen = []
output = input.map do | numbers |
new = numbers.uniq - 看到
看到+ = new
new
end
#=>输出是[[10,6,14],[],[9],[13],[16],[]]

如果要删除输出中的空列表,只需

  output.reject!( &:empty?)


I have an Array of Arrays that contains numbers in a particular order. I want to remove the duplicates out of the nested arrays, but there is a hierarchy: If a number occurs in a lower-index of the array, remove all duplicates down the Array chain.

Example: nums = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13]]

nums[0] contains [10,6,14] so any subsequent mention of 10,6,14 should be removed from the other arrays in the chain, meaning nums[2] should have 10,6 removed and only 9 should remain.

I'm having trouble doing this with nested loops, can any Ruby wizards help please?

解决方案

This should do it:

input = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13]]
seen = []
output = input.map do |numbers|
  new = numbers.uniq - seen
  seen += new
  new
end
# => output is [[10, 6, 14], [], [9], [13], [16], []]

If you want to remove the empty lists in the output, simply

output.reject!(&:empty?)

这篇关于从嵌套数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆