Skip to content

Instantly share code, notes, and snippets.

@nkabrown
Created March 22, 2016 15:14
Show Gist options
  • Save nkabrown/2733944046bdad25b553 to your computer and use it in GitHub Desktop.
Save nkabrown/2733944046bdad25b553 to your computer and use it in GitHub Desktop.
dedupe arrays in javascript
// 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