Skip to content

Instantly share code, notes, and snippets.

@ovarunendra
Last active February 17, 2017 08:47
Show Gist options
  • Save ovarunendra/58d8ae2e5584852db68e9950e64f2bee to your computer and use it in GitHub Desktop.
Save ovarunendra/58d8ae2e5584852db68e9950e64f2bee to your computer and use it in GitHub Desktop.
Deduplicate an Array
function dedup(arr) {
var hashTable = {};
return arr.filter(function (el) {
var key;
if (Object.prototype.toString.call(el) === "[object Object]") {
key = JSON.stringify(Object.keys(el).sort());
Object.keys(el).forEach(function(i){
key += JSON.stringify(el[i]);
});
} else {
key = JSON.stringify(el);
}
var match = Boolean(hashTable[key]);
return (match ? false : hashTable[key] = true);
});
}
var asd = [1, '1', 1, [1,2], [2,1], [1,2], {a:1, b:2}, {a:2, b:1}, {b:1, a:2}];
console.log(dedup(asd));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment