Last active
February 17, 2017 08:47
-
-
Save ovarunendra/58d8ae2e5584852db68e9950e64f2bee to your computer and use it in GitHub Desktop.
Deduplicate an Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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