Last active
September 11, 2015 14:50
-
-
Save victorpolko/d40a2b12dd93e7df90f9 to your computer and use it in GitHub Desktop.
JavaScript: collect duplicates in array
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
var duplicates = function(array) { | |
var iteratee = array.slice(0); | |
var seen = []; | |
return array.filter(function(element) { | |
iteratee.shift(); | |
if (seen.indexOf(element) !== -1) return false; | |
var hit = iteratee.indexOf(element) !== -1; | |
if (hit && seen.indexOf(element) === -1) seen.push(element); | |
return hit; | |
}); | |
} |
Another version based on my uniq.simple Gist
var duplicates = function(array) {
var iteratee = array.slice(0);
return array.filter(function(element) {
iteratee.shift();
return iteratee.indexOf(element) !== -1;
}).reduce(function(prev, curr) {
if (prev.indexOf(curr) === -1) prev.push(curr);
return prev;
}, []);
}
(or)
duplicates = (array) ->
iteratee = array.slice(0)
array.filter (element) ->
iteratee.shift()
iteratee.indexOf(element) != -1
.reduce (prev, curr) ->
prev.push(curr) if (prev.indexOf(curr) == -1)
return prev
, []
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The idea was to iterate over the array, removing first element from it and then to check if this element is still present in the array.
Then I added a check for already filtered elements.
CoffeeScript:
To use with any array (not recommended):
(or)