suppose I have an array [1,2,3,1,5,2]. Here 1 and 2 are the repeated elements. I want to get a new array [1,2].
How do I do that in ruby ??
suppose I have an array [1,2,3,1,5,2]. Here 1 and 2 are the repeated elements. I want to get a new array [1,2].
How do I do that in ruby ??
arr = [1,2,3,1,5,2]
arr.group_by {|e| e}.map { |e| e[0] if e[1][1]}.compact
Pretty ugly... but does the job without an n+1 problem.
arr = [1,2,3,1,5,2]
arr.select { |x| arr.count(x) > 1 } .uniq
A longer solution using reduce
should be quicker.
arr.reduce [{}, []] do |(seen, out), cur|
case seen[cur]
when :seen then
[seen.merge({cur => :added}), out << cur]
when :added then
[seen, out]
else
[seen.merge({cur => :seen}), out]
end
end.last