Created
December 7, 2020 19:08
-
-
Save DoctorDerek/0d3587f2374f343d5c9980a6b24f9f36 to your computer and use it in GitHub Desktop.
Find Unique Objects by Content (key-value pairs)
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
| // We can get Set to compare objects' key-value pairs using JSON | |
| const duplicates = [{ hello: "π" }, { hello: "π" }] | |
| const objectsJSON = duplicates.map((object) => JSON.stringify(object)) | |
| const objectsJSONSet = new Set(objectsJSON) | |
| const uniqueJSONArray = Array.from(objectsJSONSet) | |
| // Equivalent to: (using the spread operator) | |
| // const uniqueJSONArray = [...objectsJSONSet] | |
| const uniqueObjectsByContent = uniqueJSONArray.map((string) => | |
| JSON.parse(string) | |
| ) | |
| console.log(duplicates) | |
| // Output: [ { hello: "π" }, { hello: "π" } ] | |
| console.log(uniqueObjectsByContent) | |
| // Output: [ { hello: "π" } ] | |
| // Compare the behavior of the JSON-stringified objects with the | |
| // default behavior of Set, which compares object references: | |
| console.log([...new Set(duplicates)]) | |
| // Output: [ { hello: "π" }, { hello: "π" } ] | |
| // One-liner to compare objects by content (their key-value pairs): | |
| console.log( | |
| Array.from( | |
| new Set(duplicates.map((object) => JSON.stringify(object))) | |
| ).map((string) => JSON.parse(string)) | |
| ) | |
| // Output: [ { hello: "π" } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment