Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/884e321db6f9868b1951ec18e2a7733b to your computer and use it in GitHub Desktop.
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.
// 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