Skip to content

Instantly share code, notes, and snippets.

@nageshwar521
Last active June 24, 2016 11:01
Show Gist options
  • Save nageshwar521/5e696ad6783c32172ff1ea0810e1dfe9 to your computer and use it in GitHub Desktop.
Save nageshwar521/5e696ad6783c32172ff1ea0810e1dfe9 to your computer and use it in GitHub Desktop.
Easiest way to find duplicate values in a JavaScript array
var dupEleArr = [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 20, 3, 3, 3, 32, 324, 5, 52];
/*
Sort the given array and filter the array by checking
If two adjucent elements are equal and then the next immediate
element should not be equal...
Note: Tested with array of numbers, Not tested with strings
*/
var dupEle = dupEleArr.sort().filter(function(ele,i,arr){
return arr.length > 3 ? (arr[i] == arr[i+1] && arr[i+1] != arr[i+2]) : (arr.length == 2) ? (arr[i] == arr[i+1]) : true;
})
//document.querySelector("body").innerHTML = JSON.stringify(dupEle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment