Skip to content

Instantly share code, notes, and snippets.

@coolicer
Created August 8, 2013 09:19
Show Gist options
  • Save coolicer/6183080 to your computer and use it in GitHub Desktop.
Save coolicer/6183080 to your computer and use it in GitHub Desktop.
Removes all duplicates from an array
/**
* Removes all duplicates from an array (retaining only the first
* occurrence of each array element). This function modifies the
* array in place and doesn't change the order of the non-duplicate items.
*
* For objects, duplicates are identified as having the same unique ID as
* defined by {@link goog.getUid}.
*
* Runtime: N,
* Worstcase space: 2N (no dupes)
*
* @param {goog.array.ArrayLike} arr The array from which to remove duplicates.
* @param {Array=} opt_rv An optional array in which to return the results,
* instead of performing the removal inplace. If specified, the original
* array will remain unchanged.
*/
goog.array.removeDuplicates = function(arr, opt_rv) {
var returnArray = opt_rv || arr;
var seen = {}, cursorInsert = 0, cursorRead = 0;
while (cursorRead < arr.length) {
var current = arr[cursorRead++];
// Prefix each type with a single character representing the type to
// prevent conflicting keys (e.g. true and 'true').
var key = goog.isObject(current) ?
'o' + goog.getUid(current) :
(typeof current).charAt(0) + current;
if (!Object.prototype.hasOwnProperty.call(seen, key)) {
seen[key] = true;
returnArray[cursorInsert++] = current;
}
}
returnArray.length = cursorInsert;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment