Skip to content

Instantly share code, notes, and snippets.

@victorpolko
Last active September 11, 2015 14:50
Show Gist options
  • Save victorpolko/d40a2b12dd93e7df90f9 to your computer and use it in GitHub Desktop.
Save victorpolko/d40a2b12dd93e7df90f9 to your computer and use it in GitHub Desktop.
JavaScript: collect duplicates in array
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;
});
}
@victorpolko
Copy link
Author

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