Map and Set
Data Types: Map and Set
What is a Map in JavaScript?
View Answer:
// Creating a new Map
let myMap = new Map();
// Adding key-value pairs
myMap.set('name', 'John');
myMap.set('age', 30);
// Accessing values
console.log(myMap.get('name')); // Output: John
console.log(myMap.get('age')); // Output: 30
// Checking if a key exists
console.log(myMap.has('name')); // Output: true
// Deleting a key-value pair
myMap.delete('age');
// Checking the size of the Map
console.log(myMap.size); // Output: 1
// Clearing all key-value pairs
myMap.clear();
console.log(myMap.size); // Output: 0
What is the difference between Map and Object in JavaScript?
View Answer:
let map = new Map();
map.set('1', 'str1'); // a string key
map.set(1, 'num1'); // a numeric key
map.set(true, 'bool1'); // a boolean key
// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
console.log(map.get(1)); // 'num1'
console.log(map.get('1')); // 'str1'
console.log(map.size); // 3
What are some methods and properties that a Map implements?
View Answer:
Methods and properties are as follows:
- new Map() – constructs the map.
- map.set(key, value) — saves the value as a function of the key.
- map.get(key) – returns the value specified by the key or undefined if the key does not exist in the map.
- map.has(key) – If the key exists, it returns true; otherwise, it returns false.
- map.delete(key) - deletes the value specified by the key.
- map.clear() — clears the map completely.
- map.size – The number of elements currently on the map gets returned.
let contacts = new Map();
// stores the value by the key
contacts.set('Raymond', { phone: '213-555-1234', address: '123 N 1st Ave' });
contacts.has('Jessie'); // false 'Jessie' does not exist
contacts.get('Hilary'); // returns undefined
// stores as the value by the key
contacts.set('Hilary', { phone: '617-555-4321', address: '321 S 2nd St' });
console.log(contacts); // Map returns Hilary and Raymond
contacts.delete('Raymond'); // deletes Raymond returns true
contacts.get('Hilary'); // returns values
console.log(contacts.size); // returns 1
What is one of the most notable and vital Map features in JavaScript?
View Answer:
let john = { name: 'John' };
let ben = { name: 'Ben' };
let visitsCountObj = {}; // try to use an object
visitsCountObj[ben] = 234; // try to use ben object as the key
visitsCountObj[john] = 123; // try to use john object as the key, ben object will get replaced
// That's what got written!
console.log(visitsCountObj['[object Object]']); // 123
console.log(visitsCountObj[ben]); // ben returns 123 because it was overwritten by john
How does the Map Object compare keys?
View Answer:
Which map methods can you use to iterate over a Map Object?
View Answer:
let recipeMap = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50],
]);
// iterate over keys (vegetables)
for (let vegetable of recipeMap.keys()) {
console.log(vegetable); // cucumber, tomatoes, onion
}
// iterate over values (amounts)
for (let amount of recipeMap.values()) {
console.log(amount); // 500, 350, 50
}
let recipeMap = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50],
]);
// We can also iterate over entries using a forEach()
recipeMap.forEach((quantity, veg) => console.log(`${veg}, ${quantity}`));
Besides the key, values, and entries methods, is there another method you can use to iterate over a Map Object?
View Answer:
let recipeMap = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50],
]);
// iterate over entries using a forEach()
recipeMap.forEach((quantity, veg) => console.log(`${veg}, ${quantity}`));
Can you set properties for Map the same way you add properties for a regular object-literal?
View Answer:
// Wrong Way
let wrongMap = new Map();
wrongMap['bla'] = 'blaa';
wrongMap['bla2'] = 'blaaa2';
console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }
// Any attempt to revert back to Maps built-in methods will fail
wrongMap.has('bla'); // false
wrongMap.delete('bla'); // false
console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }
// Right way for storing data in the Map - set(key, value) method.
let contacts = new Map();
contacts.set('Jessie', { phone: '213-555-1234', address: '123 N 1st Ave' });
contacts.has('Jessie'); // true
contacts.get('Hilary'); // undefined
contacts.set('Hilary', { phone: '617-555-4321', address: '321 S 2nd St' });
contacts.get('Jessie'); // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond'); // false
contacts.delete('Jessie'); // true
console.log(contacts.size); // 1
Can you add properties to a Map using bracket notation?
View Answer:
Can you convert a plain object into a Map in JavaScript?
View Answer:
let obj = {
name: 'John',
age: 30,
};
let map = new Map(Object.entries(obj));
console.log(map.get('name')); // John
What is the main difference between Object.entries and Object.fromEntries methods regarding the Map Object?
View Answer:
let map = new Map();
map.set('banana', 1);
map.set('orange', 2);
map.set('meat', 4);
let obj = Object.fromEntries(map.entries()); // make a plain object (*)
// done!
// obj = { banana: 1, orange: 2, meat: 4 }
console.log(obj.orange); // 2
let obj = {
name: 'John',
age: 30,
};
let map = new Map(Object.entries(obj));
console.log(map.get('name')); // John
How does the Set Object function in JavaScript?
View Answer:
let set = new Set();
let john = { name: 'John' };
let pete = { name: 'Pete' };
let mary = { name: 'Mary' };
// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);
// set keeps only unique values
console.log(set.size); // 3
for (let user of set) {
console.log(user.name); // John (then Pete and Mary)
}
What are the obvious differences between a Set and Array objects?
View Answer:
// Array
let array = [1, 2, 2, 3];
console.log(array[1]); // outputs: 2
console.log(array.length); // outputs: 4
// Set
let set = new Set([1, 2, 2, 3]);
console.log(set.has(2)); // outputs: true
console.log(set.size); // outputs: 3, because "2" only counts once.
What is the best way to loop/iterate over a Set in JavaScript?
View Answer:
let set = new Set(['oranges', 'apples', 'bananas']);
for (let value of set) console.log(value);
// the same with forEach:
set.forEach((value, valueAgain, set) => {
console.log(value);
});
let set = new Set(['oranges', 'apples', 'bananas']);
for (let i = set.values(), val = null; (val = i.next().value); ) {
console.log(val);
}
You can also use a traditional iterative for loop, but it is much more complex and not recommended.
What is the difference between the set() and add() methods in Map?
View Answer:
Here is a simple JavaScript code example showing the use of set()
in a Map
and add()
in a Set
:
// Map
let map = new Map();
map.set('key1', 'value1');
console.log(map.get('key1')); // outputs: 'value1'
// Set
let set = new Set();
set.add('value1');
console.log(set.has('value1')); // outputs: true
In the above example, set()
is used to add key-value pairs to the Map
and add()
is used to add unique values to the Set
.
How can you convert a Map to an array?
View Answer:
let map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
// Convert Map to Array using Array.from()
let array1 = Array.from(map);
console.log(array1); // outputs: [ ['key1', 'value1'], ['key2', 'value2'] ]
// Convert Map to Array using spread operator
let array2 = [...map];
console.log(array2); // outputs: [ ['key1', 'value1'], ['key2', 'value2'] ]`
What is the difference between the has() and get() methods in Map?
View Answer:
Here's a simple JavaScript code example showing the use of has()
and get()
in a Map
:
let map = new Map();
map.set('key1', 'value1');
console.log(map.has('key1')); // outputs: true
console.log(map.get('key1')); // outputs: 'value1'
console.log(map.has('key2')); // outputs: false
console.log(map.get('key2')); // outputs: undefined
In the above example, has('key1')
returns true because 'key1' exists in the map, and get('key1')
returns 'value1' which is the value associated with 'key1'. However, 'key2' does not exist in the map, so has('key2')
returns false and get('key2')
returns undefined.
Can you use objects as keys in a Map? If so, how does it compare them?
View Answer:
Here's a JavaScript code example showing how to use objects as keys in a Map
:
let obj1 = {name: 'Object 1'};
let obj2 = {name: 'Object 2'};
let map = new Map();
map.set(obj1, 'value1');
console.log(map.has(obj1)); // outputs: true
console.log(map.get(obj1)); // outputs: 'value1'
console.log(map.has(obj2)); // outputs: false
console.log(map.get(obj2)); // outputs: undefined
In this example, obj1
and obj2
are different instances, so they are considered distinct keys. map.has(obj2)
returns false and map.get(obj2)
returns undefined, even though obj1
and obj2
have the same structure.
What is a Set in JavaScript?
View Answer:
let set = new Set();
// Adding values to the set
set.add(1);
set.add('Hello');
set.add(true);
console.log(set.size); // outputs: 3
// Checking if a value exists in the set
console.log(set.has('Hello')); // outputs: true
console.log(set.has(2)); // outputs: false
// Deleting a value from the set
set.delete(1);
console.log(set.size); // outputs: 2
// Iterating over the set
for (let item of set) {
console.log(item);
}
How do you add an element to a Set?
View Answer:
let set = new Set();
// Adding elements to the set
set.add(1);
set.add('Hello');
set.add(true);
console.log(set); // outputs: Set { 1, 'Hello', true }
How do you remove an element from a Set?
View Answer:
let set = new Set();
// Adding elements to the set
set.add(1);
set.add('Hello');
set.add(true);
console.log(set); // outputs: Set { 1, 'Hello', true }
// Removing an element from the set
set.delete('Hello');
console.log(set); // outputs: Set { 1, true }
How can you determine the size of a Set?
View Answer:
let set = new Set();
// Adding elements to the set
set.add(1);
set.add('Hello');
set.add(true);
console.log(set.size); // outputs: 3
How can you convert a Set to an array?
View Answer:
let set = new Set();
set.add(1);
set.add('Hello');
set.add(true);
// Convert Set to Array using Array.from()
let array1 = Array.from(set);
console.log(array1); // outputs: [1, 'Hello', true]
// Convert Set to Array using spread operator
let array2 = [...set];
console.log(array2); // outputs: [1, 'Hello', true]