Search code examples
javascriptarraysecmascript-6setjavascript-objects

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.

Solution

  • 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.