Created
December 7, 2020 19:08
-
-
Save DoctorDerek/7e8ba7a07b0aea05020e1c7ed73bb860 to your computer and use it in GitHub Desktop.
Find Unique JavaScript Objects by Object Reference
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
| // By default, Set compares JS object references | |
| const myObject = { hello: "π" } | |
| const objectsArray = [myObject, myObject] | |
| const objectsSet = new Set(objectsArray) | |
| const uniqueObjectReferences = Array.from(objectsSet) | |
| // Equivalent to: (using the spread operator) | |
| // const uniqueObjectReferences = [...objectsSet] | |
| console.log(objectsArray) | |
| // Output: [ { hello: "π" }, { hello: "π" } ] | |
| console.log(uniqueObjectReferences) | |
| // Output: [ { hello: "π" } ] | |
| // One-liner: | |
| console.log([...new Set([myObject, myObject])]) | |
| // Output: [ { hello: "π" } ] | |
| // Compare to different objects with same contents: | |
| console.log([...new Set([{ id: 1 }, { id: 1 }])]) | |
| // Output: [ { id: 1 }, { id: 1 } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment