Created
March 22, 2016 15:14
-
-
Save nkabrown/2733944046bdad25b553 to your computer and use it in GitHub Desktop.
dedupe arrays in javascript
This file contains 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
// deduplicate array of primitives | |
let deduped = arr.filter((el, i, arr) => arr.indexOf(el) === i); | |
// or | |
deduped = Array.from(new Set(arr)); | |
// deduplicate array of ojects using a hash table | |
function dedupe(arr) { | |
let hashTable = {}; | |
return arr.filter(function(el) { | |
let key = JSON.stringify(el); // or JSON.stringify(el.prop) | |
let match = Boolean(hashTable[key]); | |
return (match ? false : hashTable[key] = true); | |
}); | |
} | |
deduped = dedupe(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment