Skip to content

Instantly share code, notes, and snippets.

@grevych
Last active March 2, 2019 00:02
Show Gist options
  • Save grevych/4a1cfa631bdc3a8c130ff446d44488bc to your computer and use it in GitHub Desktop.
Save grevych/4a1cfa631bdc3a8c130ff446d44488bc to your computer and use it in GitHub Desktop.
Find all duplicates in an array. The elements in the array have no restrictions, but in this algorithm we'll work specifically with integers.
/*
Example:
duplicates([1, 21, -4, 103, 21, 4, 1]);
result = [1, 21]
*/
function find_duplicates(arr) {
const duplicates = {};
arr.forEach((item) => {
if (duplicates[item])
duplicates[item]++;
} else {
duplicates[item] = 1;
}
});
return Object
.keys(duplicates)
.filter(key => duplicates[key] > 1);
}
console.log(find_duplicates([1, 21, -4, 103, 21, 4, 1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment