how to get only the duplicatet items from an array

N

Nico Landgraf

hi all,

is there a oneline to get only the duplicatet item from an array?

i have an array like this
aTemp = [1, 1, 2, 2, 3, 4]
and i want to know, which items are duplicatet.

i thought i can do it like
aTemp - aTemp.uniq

[1, 1, 2, 2, 3, 4] - [1, 2, 3, 4] => [1, 2]
like inside the manual

but i get only an empty array


so i found an bad solution and hope you can help me to get the right way.

thanks for your help
nico
 
N

Nico Landgraf

thanks paul,

looks like my way.
i hoped there is a smarter way in ruby.

Paul said:
Nico said:
i have an array like this
aTemp = [1, 1, 2, 2, 3, 4]
and i want to know, which items are duplicatet.

/ ...
so i found an bad solution and hope you can help me to get the right way.

#!/usr/bin/ruby -w

a = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9]

dups = []

hash = {}

a.each do |item|
dups << item if hash[item]
hash[item] = true
end

p dups

[1, 1, 1, 1, 2, 2, 2, 9, 9]
 
W

Wilson Bilkovich

hi all,

is there a oneline to get only the duplicatet item from an array?

i have an array like this
aTemp = [1, 1, 2, 2, 3, 4]
and i want to know, which items are duplicatet.

i thought i can do it like
aTemp - aTemp.uniq

[1, 1, 2, 2, 3, 4] - [1, 2, 3, 4] => [1, 2]
like inside the manual

but i get only an empty array


so i found an bad solution and hope you can help me to get the right way.

Here's one way:
irb(main):001:0> h = Hash.new(0)
=> {}
irb(main):002:0> array = [1,1,2,2,3,4,1]
=> [1, 1, 2, 2, 3, 4, 1]
irb(main):003:0> duplicates = array.select {|e| h[e] += 1; h[e] == 1}
=> [1, 2, 3, 4]
irb(main):004:0>

There are shorter ways, but I find that one to be pretty readable. The
resulting array doesn't contain duplicates, just one each of the
entries that appeared multiple times in the input array.

It also makes it easy to find out how many times something appeared,
if you need that.

h[1] will return 3, for example.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top