Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Last active December 20, 2015 21:59
Show Gist options
  • Save ianpgall/6201688 to your computer and use it in GitHub Desktop.
Save ianpgall/6201688 to your computer and use it in GitHub Desktop.
JavaScript functions that remove duplicates from an array
var RemoveDuplicates = (function () {
"use strict";
var inPlace, getCopy;
inPlace = function (arr) {
var i, j, cur, found;
for (i = arr.length - 1; i >= 0; i--) {
cur = arr[i];
found = false;
for (j = i - 1; !found && j >= 0; j--) {
if (cur === arr[j]) {
if (i !== j) {
arr.splice(i, 1);
}
found = true;
}
}
}
return arr;
};
getCopy = function (arr) {
var ret, len, i, j, cur, found;
ret = [];
len = arr.length;
for (i = 0; i < len; i++) {
cur = arr[i];
found = false;
for (j = 0; !found && (j < len); j++) {
if (cur === arr[j]) {
if (i === j) {
ret.push(cur);
}
found = true;
}
}
}
return ret;
};
return {
inPlace: inPlace,
getCopy: getCopy
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment