Skip to content

Instantly share code, notes, and snippets.

@niisar
Created January 2, 2017 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niisar/73755a0518b00fc64ce8de670f2307c9 to your computer and use it in GitHub Desktop.
Save niisar/73755a0518b00fc64ce8de670f2307c9 to your computer and use it in GitHub Desktop.
find duplicate in JavaScript
//this prototype function checks if an element is already in the array or not
//go through all the array and push the element to result if it is not
//this way we can eliminate duplicates
//result will contain the resultant array
Array.prototype.contains = function(k) {
for ( var p in this)
if (this[p] === k)
return true;
return false;
};
function findDuplicates(Numbers) {
var arrayLength = Numbers.length, i, j, result = [];
for (i = 0; i < arrayLength; i++) {
for (j = 0; j < arrayLength; j++) {
if (a[i] == a[j] && i != j && !result.contains(a[i])) {
result.push(a[i]);
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment