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

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:

duplicates = (array) ->
  iteratee = array.slice(0)
  seen = []

  array.filter (element) ->
    iteratee.shift()

    return false if seen.indexOf(element) != -1

    hit = iteratee.indexOf(element) != -1
    seen.push(element) if hit && seen.indexOf(element) == -1

    hit

To use with any array (not recommended):

Array.prototype.duplicates = function() {
  var iteratee = this.slice(0);
  var seen = [];

  return this.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;
  });
}

(or)

Array.prototype.duplicates = ->
  iteratee = this.slice(0)
  seen = []

  this.filter (element) ->
    iteratee.shift()

    return false if seen.indexOf(element) != -1

    hit = iteratee.indexOf(element) != -1
    seen.push(element) if hit && seen.indexOf(element) == -1

    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