我有一个数组如下:
['a=1', 'b=2', 'a=2']
我想过滤数组,使元素在第一个字符方面是唯一的。我想要结果:
['a=1', 'b=2']
关于上述问题,["a", "b", "a"]
变为["a", "b"]
。
感谢所有帮助。
答案 0 :(得分:5)
这是来自Array#uniq的评论文档:
b = [["student","sam"], ["student","george"], ["teacher","matz"]]
b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
所以b.uniq{ |s| s[0] }
似乎是唯一的 - 如果是每个字符串的第一个字符的数组。
答案 1 :(得分:1)
出于好奇(感谢@Phlip输入我无耻地被盗):
b = [["student","sam"], ["student","george"], ["teacher","matz"]]
b.reverse.to_h.to_a.reverse
#⇒ [["student", "sam"], ["teacher", "matz"]]