Barath adhithya
Barath adhithya

Reputation: 3

After trying this example, feeling confused on the basics of Maps and Set in Javascript

I am trying to apply some examples to better understand the difference of Map and Set and the behaviour of each one seems confusing. Look at the examples and output below

Map example:

let nameMap = new Map([
  ['name', 'stack'],
  ['name', 'overflow'],
  ['domain', 'technology']
]);

// iterate over keys (nameMap)
for (let name of nameMap) {
  console.log(JSON.stringify(name)); 
}

output:

["name","overflow"]
["domain","technology"]

Set Example:

let nameSet = new Set([
  ['name', 'stack'],
  ['name', 'overflow'],
  ['domain', 'technology']
]);

// iterate over keys (nameSet)
for (let name of nameSet) {
  console.log(JSON.stringify(name));
}

output:

["name","stack"]
["name","overflow"]
["domain","technology"]
  1. My question is why map returns only the second occurence of two similar objects?
  2. Set returns all three objects even though first two keys and values being same, while it supposed to delete one of them.

Upvotes: 0

Views: 39

Answers (3)

deceze
deceze

Reputation: 522441

A Map is a container for key-value pairs. In your input, name and domain will become keys. Since a key can only exist once, the key name gets deduplicated.

A Set is an array of values which deduplicates the values themselves. Since there aren't any identical values in your input, all are retained.

Upvotes: 0

Quentin
Quentin

Reputation: 944084

My question is why map returns only the second occurence of two similar objects?

Because a Map contains a set of key-value pairs. You can only have one value per key. In the constructor, each array is represents [key, value]). The second bit of data with the key 'name' overwrites the first one.

Set returns all three objects even though first two keys and values being same, while it supposed to delete one of them.

A set stores a set of unique values. Each array (like ['name', 'stack']) is one value.

Upvotes: 2

Jack Bashford
Jack Bashford

Reputation: 44135

Because Sets are like arrays - they just store the values in a list. Therefore, the constructor will add all three arrays to the new Set as values. The Map constructor is similar to Object.fromEntries - the first item in each sub-array is the key, the second the value. You can't store keys in a Set, only values - so the two items have to be exactly the same, and a primitive, to be excluded from the Set.

Upvotes: 0

Related Questions