Last active
March 2, 2019 00:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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