Problem
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.
Example:
Input: ["a", "b", "c", "b", "b", "c", "b", "d", "m", "n", "n"];
Output: ["b", "c", "n"];
Solutions Using JS
Solution:
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)) {
duplicates.push(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:
duplicates.append(value)
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.
Discussions