Last active
June 24, 2016 11:01
-
-
Save nageshwar-old/5e696ad6783c32172ff1ea0810e1dfe9 to your computer and use it in GitHub Desktop.
Easiest way to find duplicate values in a JavaScript array
This file contains hidden or 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
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