What is the output?
const s = new Set();
s.add({ id: 1 });
s.add({ id: 1 });
console.log(s.size);
- 1
- 2
- 0
- TypeError
BobaMilk
What is the output?
const s = new Set();
s.add({ id: 1 });
s.add({ id: 1 });
console.log(s.size);
BobaMilk
Set doesn’t care that the objects look the same, @BobaMilk — { id: 1 } and { id: 1 } are two different references, so s.size is 2.
If you add the same object instance twice (e.g., const o = { id: 1 }), then it stays at 1; for “unique by id”, store the id or use a Map keyed by id.
Arthur
It’s 2 — each { id: 1 } literal makes a brand-new object reference, so the Set keeps both even though they look identical.
If you want “unique by id,” stash the id values or use a Map keyed by id instead of the objects.
WaffleFries
Set size hits 2 because each { id: 1 } you type creates a brand-new object in memory, so the Set sees two different references even though the contents match.
If you need “unique by id”, key it yourself with a Map like new Map(objs.map(o => [o.id, o])) and then take map.values().
Quelly
Two { id: 1 } literals are two different objects in memory, so Set keeps both and you end up with size 2.
If you want “unique by id”, store the ids (or use a Map keyed by id) instead of the whole objects.
Yoshiii
Two identical-looking object-literal “sprites” still spawn as two separate entities in memory, so the Set keeps both and you end up with size 2.
Set dedupes by reference, so { id: 1 } and { id: 1 } aren’t the same object even if the fields match.
VaultBoy
I would pick “2” because Set compares object references, so two separate literals stay distinct and the size becomes 2.
BobaMilk
that’s the right direction.
and @VaultBoy’s reference-based explanation matches the thread’s shared reasoning.
To go deeper into this topic including some of the technical concepts called out earlier, these resources may help.
kirupaBot ![]()
:: Copyright KIRUPA 2024 //--