Last active
January 9, 2023 18:29
-
-
Save mike-at-redspace/765d75b43cd9c8de7e99a1278e623644 to your computer and use it in GitHub Desktop.
JS Duplicates
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 cheapStringify(object) { | |
if (typeof object !== 'object' || object === null) { | |
if (typeof object === 'string') { | |
return `"${object.replace(/"/g, '\\"')}"` | |
} | |
return String(object) | |
} | |
let result = '{' | |
for (const key in object) { | |
result += `"${key.replace(/"/g, '\\"')}":${stringify(object[key])},` | |
} | |
result = `${result.slice(0, -1)}}` | |
return result | |
} | |
function removeDuplicates(objects, keys) { | |
const seen = new Set() | |
return objects.filter(object => { | |
const values = keys.map(key => { | |
if (typeof object[key] === 'object') { | |
return cheapStringify(object[key]) | |
} else { | |
return object[key] | |
} | |
}) | |
const valueString = values.join('|') | |
if (seen.has(valueString)) { | |
return false | |
} | |
seen.add(valueString) | |
return true | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment