DEV Community

Discussion on: 1 line of code: How to remove all duplicates from an Array

Collapse
 
humansprout profile image
Erik Waters • Edited

I think they mean it won't behave as expected if the array contains similar objects that have different references

const originalObject = {}
const boundToOriginalObject = originalObject
const newObjectThatLooksLikeOriginal = {}
const arr = [originalObject, boundToOriginalObject, newObjectThatLooksLikeOriginal]
const dedupe = [ ...new Set(arr)]
dedupe // [{}, {}]
// deduping removes the duplicate reference but not similar objects
const mutation = {a: 1}
Object.assign(dedupe[1], mutation)
originalObject // {}
newObjectThatLooksLikeOriginal // { a: 1 }
// this proves which references remained in the deduped array prior to mutation
Enter fullscreen mode Exit fullscreen mode

It might be helpful to clarify that dedupe will remove duplicate bindings but not similar objects with a different binding