# How to find the repeated elements in a vector

Is there a way to write a function where the input is a vector and the output is the elements in the vector that are repeated?

I was trying to use something along the lines:

f[x_] := DeleteCases[Gather[x], Length[#1] != 1]


Of course this doesn't work, giving me this output:

input: f[{1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11}]
output: {{1, 1}, {2, 2, 2}, {4}, {3}, {5, 5}, {7}, {8}, {9}, {0}, {11}}


If I was able to delete the elements with Length 1, I could delete easily construct the output

• Maybe f[x_] := Select[Gather[x], Length[#] != 1 &][[All, 1]].
– JimB
Apr 23, 2021 at 22:27

DeleteCases requires a pattern, not a function, as second argument:

f[x_] := DeleteCases[Gather[x], {_}]

f[{1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11}]
(*    {{1, 1}, {2, 2, 2}, {5, 5}}    *)


You may use Tally and ConstantArray.

With

lst = {1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11}


and

repeatedElements[lst_List] := ConstantArray @@@ DeleteCases[Tally[lst], {_, 1}]


then

repeatedElements[lst]

{{1, 1}, {2, 2, 2}, {5, 5}}


Hope this helps.

list = {1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11};


### Gather + Cases

ClearAll[duplicateElements1]
duplicateElements1 = Cases[{_, __}] @* Gather;

duplicateElements1 @ list

{{1, 1}, {2, 2, 2}, {5, 5}}


### Counts + Select + KeyValueMap:

ClearAll[duplicateElements2]
duplicateElements2 = KeyValueMap[ConstantArray] @* Select[GreaterThan @ 1] @* Counts;

duplicateElements2 @ list

{{1, 1}, {2, 2, 2}, {5, 5}}


### GroupBy + Values

ClearAll[duplicateElements3]
duplicateElements3 = Values @ GroupBy[#, Identity, If[Length@# > 1, #, Nothing] &] &;

duplicateElements3 @ list

{{1, 1}, {2, 2, 2}, {5, 5}}


You could use ResourceFunction["Duplicates"]

list = {1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11};
Gather@ResourceFunction["Duplicates"]@list

(* result: {{1, 1}, {2, 2, 2}, {5, 5}} *)


And here's another way using undocumented function GeneralUtilitiesFindDuplicates

With[{c = Counts@list},
ConstantArray[#, c[#]] & /@ GeneralUtilitiesFindDuplicates[list]
]