从数组数组中删除重复对

时间:2014-03-03 19:39:27

标签: ruby arrays

我有一组对,如下例所示:

array = [["human KIR2DS1", 446.0], ["mouse BMP-4", 446.0], ["mouse BMP-4", 446.0], ["mTIMP2 lot DAAP01", "435a"], ["hKIR3DL3 lot DDBL01", "435a"]]

我想删除数组中的重复对。最简单的方法是什么?

2 个答案:

答案 0 :(得分:3)

使用Array#uniq

array.uniq
# => [["human KIR2DS1", 446.0], ["mouse BMP-4", 446.0], ["mTIMP2 lot DAAP01", "435a"], ["hKIR3DL3 lot DDBL01", "435a"]]

或者如果你想修改原始数组:

array.uniq!
array # => [["human KIR2DS1", 446.0], ["mouse BMP-4", 446.0], ["mTIMP2 lot DAAP01", "435a"], ["hKIR3DL3 lot DDBL01", "435a"]]

答案 1 :(得分:0)

这也可以用来筛选出重复项并返回一个新的数组,其中没有重复项。我使用传播运算符“ ...”

function unique(array) {
    return [...new Set(array)];
}