删除数组中的重复项,并将其第二个值添加到数组中

时间:2023-02-06 12:14:29

I want to convert:

我想转换:

[["val1", "1"], ["val2", "2"], ["val1", "3"], ["val3", "4"], ["val2", "5"], ["val2", "6"]]

to:

:

[["val1", ["1", "3"]], ["val2", ["2", "5", "6"]], ["val3", ["4"]]

Duplicates of the first value ("val1") of the subarrays are removed, and their second values ("1" and "3") are put together in an array.

删除子数组的第一个值(“val1”)的重复,将它们的第二个值(“1”和“3”)放在一个数组中。

I could call uniq on the array, but that only fixes half the problem. I gave it my best crack:

我可以在数组上调用uniq,但这只能解决问题的一半。我尽了最大的努力:

  • Store the first value (we can call value a) of the 2d array into another 2d array and calling .uniq on the new array.
  • 将2d数组的第一个值(我们可以调用value a)存储到另一个2d数组中,并在新的数组中调用.uniq。
  • The new 2d array has an empty array in value b.
  • 新的2d数组在值b中有一个空数组。
  • Then loop through the new array with an if statement comparing the original arrays value a to the new arrays value a. If value a from the original array matches val a from the new array add its b value to the new arrays b value array.
  • 然后使用if语句对新数组进行循环,该语句将原数组的值a与新数组的值a进行比较。

This was my approach but there is most likely an easier approach.

这是我的方法,但很可能有更简单的方法。

2 个解决方案

#1


6  

[["val1", "1"], ["val2", "2"], ["val1", "3"], ["val3", "4"], ["val2", "5"], ["val2", "6"]]
.group_by(&:first).map{|k, a| [k, a.map(&:last)]}
# => [["val1", ["1", "3"]], ["val2", ["2", "5", "6"]], ["val3", ["4"]]]

#2


1  

Here is one more way to accomplish the same:

还有一种方法可以达到同样的效果:

ary.each_with_object(Hash.new {|h, k| h[k] = []}) do |i, h|  
  h[i.first] << i.last 
end.to_a
#=> [["val1", ["1", "3"]], ["val2", ["2", "5", "6"]], ["val3", ["4"]]]

We use a Hash which will initialise the keys with empty array, and it helps in the block to push the values into the array without having to do nil check.

我们使用一个散列,它将用空数组初始化键,并且它在块中帮助将值推入数组,而无需进行nil检查。

#1


6  

[["val1", "1"], ["val2", "2"], ["val1", "3"], ["val3", "4"], ["val2", "5"], ["val2", "6"]]
.group_by(&:first).map{|k, a| [k, a.map(&:last)]}
# => [["val1", ["1", "3"]], ["val2", ["2", "5", "6"]], ["val3", ["4"]]]

#2


1  

Here is one more way to accomplish the same:

还有一种方法可以达到同样的效果:

ary.each_with_object(Hash.new {|h, k| h[k] = []}) do |i, h|  
  h[i.first] << i.last 
end.to_a
#=> [["val1", ["1", "3"]], ["val2", ["2", "5", "6"]], ["val3", ["4"]]]

We use a Hash which will initialise the keys with empty array, and it helps in the block to push the values into the array without having to do nil check.

我们使用一个散列,它将用空数组初始化键,并且它在块中帮助将值推入数组,而无需进行nil检查。