阵列中的删除重复项,并有添加到阵列中的第二值 [英] Remove duplicates in an array and have its second value added to an array

查看:87
本文介绍了阵列中的删除重复项,并有添加到阵列中的第二值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换:

  [VAL1,1],[val2的,2],[VAL1,3],[VAL3,4 ],[val2中,5],[val2的,6]]

  [VAL1,[1,3],[val2的,[2,5,6]],[ VAL3,[4]]

第一个值的重复(VAL1)的子阵列删除,他们的第二个值(13)被一起放在一个阵列。

我可以打电话给 uniq的阵列上,但只有一半修复的问题。我给我最好的裂缝:


  • 店铺的第一个值(我们可以称之为价值)的二维数组成
    另一个二维数组并调用.uniq新阵列上。

  • 新的二维数组有值B空数组。

  • 然后通过新的数组循环与if语句比较
    原来阵列看重到新阵列看重。如果从价值
    原数组匹配VAL从一个新的阵列添加它的b值
    新的数组b值为数组。

这是我的做法,但也很可能是一个更简单的方法。


解决方案

  [VAL1,1],[val2的,2],[VAL1 ,3],[VAL3,4],[val2中,5],[val2的,6]]
.group_by(安培;:第一).MAP {| K,A | [K,a.map(安培;:最后一个)]}
#=> [[val1中,[1,3]],[val2的,[2,5,6]],[VAL3,[4]]]

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.

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

  • Store the first value (we can call value a) of the 2d array into another 2d array and calling .uniq on the new array.
  • The new 2d array has an empty array in value 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.

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

解决方案

[["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"]]]

这篇关于阵列中的删除重复项,并有添加到阵列中的第二值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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