Find duplicate or repeated elements in an array


Write a program to extract duplicate values out of array. Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array.


Input: ["a", "b", "c", "b", "b", "c", "b", "d", "m", "n", "n"];
Output: ["b", "c", "n"];

Solutions Using JS

const arr = ["a", "b", "c", "b", "b", "c", "b", "d", "m", "n", "n"];

let keys = {};
let duplicates = [];
arr.forEach((k) => {
  keys[k] = (keys[k] || 0) + 1;
  if (keys[k] > 1 && !duplicates.includes(k)) {

console.log(duplicates); //["b", "c", "n"]

Solutions Using Python

Solution 1:
arr = ["a", "b", "c", "b", "b", "c", "b", "d", "m", "n", "n"]

duplicates = []

for value in arr:
  if arr.count(value) > 1 and value not in duplicates:

print(duplicates) #["b", "c", "n"]
Solution 2:

Using Set

arr = ["a", "b", "c", "b", "b", "c", "b", "d", "m", "n", "n"]
duplicates = list(set([x for x in arr if arr.count(x) > 1]))
print(duplicates)  #["b", "c", "n"]

To sum it up

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter here.

Please don't hesitate to drop a comment here if I miss anything. Also, let me know if I can make the post better.


Up next