Created
October 30, 2020 23:54
-
-
Save DoctorDerek/884e321db6f9868b1951ec18e2a7733b to your computer and use it in GitHub Desktop.
JavaScript considers different objects with the same value to be unique items with different object references when using Set.
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
// Different JavaScript objects have different | |
// object references, even with the same values: | |
const someArray = [1] | |
const otherArray = [1] | |
// Different references even though both are [1] | |
console.log(`Does someArray === someArray?`) | |
console.log(`${someArray === someArray}`) | |
// Output: true because of same object reference | |
console.log(`Does someArray === otherArray?`) | |
console.log(`${someArray === otherArray}`) | |
// Output: false because of different references | |
// We can use Set to find the unique references | |
const arrays = [someArray, someArray, otherArray] | |
const uniqueArrays = Array.from(new Set(arrays)) | |
console.log(`${uniqueArrays.length} unique refs`) | |
// Output: 2 unique refs, someArray & otherArray | |
// Example using objects instead of arrays | |
const myObj = { hello: "world ๐" } | |
const moonObj = { hello: "moon ๐" } | |
const objArrays = [myObj, myObj, moonObj, moonObj] | |
const uniqueObjArr = Array.from(new Set(arrays)) | |
console.log(`${uniqueObjArr.length} unique refs`) | |
// Output: 2 unique refs, myObj & moonObj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment