Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save DoctorDerek/7e8ba7a07b0aea05020e1c7ed73bb860 to your computer and use it in GitHub Desktop.

Select an option

Save DoctorDerek/7e8ba7a07b0aea05020e1c7ed73bb860 to your computer and use it in GitHub Desktop.
Find Unique JavaScript Objects by Object Reference
// 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