I'm looking to gain a better understanding of the differences between Map and Set by applying some examples. However, I find the behavior of each to be quite confusing. Let's take a closer look at the examples and their respective outputs 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"]
- Why does map only return the second occurrence of two similar objects?
- Set returns all three objects even though the first two keys and values are the same, when it should actually remove one of them. Why is this happening?