JS Map & Set

HTML
CSS
C#
SQL

Map and Set

Map Object:

The JavaScript Map object is used to map keys to values. It stores each element as a key-value pair. It operates the elements such as search, update and delete based on a specified key.

A Map holds key-value pairs where the keys can be any datatype. A Map remembers the original insertion order of the keys. A Map has a property that represents the size of the map.

Syntax:

new Map([iterable])

Parameter :

Iterable – It represents an array and other iterable objects whose elements are in the form of a key-value pair.

Example:

Points to Remember:

– A Map object does not allow duplicate keys. Each key must be unique.
– A Map object can contain duplicate values.
– Keys and values can be of any type, supporting both objects and primitive values.
– A Map object iterates its elements in the order of their insertion.

Set Object:

The Set object is a collection of unique values where each value must be unique. It provides efficient methods for adding, deleting, and checking the existence of elements.

Syntax:

new Set([iterable])  

Parameter :

Iterable – It represents an iterable object whose elements will be added to the new Set.

Example:

Points to Remember:

– A Set object uses the concept of keys internally, but these keys are the same as the values.
– A Set object cannot contain duplicate values. Each value must be unique.
– A Set object iterates its elements in the order of their insertion.

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a JS program to Map an Element using Map Object in JS. For Example, create a Map Object Name called Fruits and Map the Different Name of Fruits with Different Values.

The task is to write a JavaScript program that uses a Map object to map different names of fruits to their respective values.
1. Create a Map Object:
Use the Map object in JavaScript to create a map of fruits.
2. Map Fruits to Values:
Add entries to the Map where the keys are different names of fruits, and the values are associated values or any related information.

Here’s an example program:

// Step 1: Create a Map Object
const fruitsMap = new Map();

// Step 2: Map Fruits to Values
fruitsMap.set(“Apple”, “Red and sweet”);
fruitsMap.set(“Banana”, “Yellow and curved”);
fruitsMap.set(“Orange”, “Orange and citrusy”);
fruitsMap.set(“Grapes”, “Small and juicy”);

// Display the mapped values
console.log(“Fruits and their descriptions:”);

// Iterate through the Map entries
for (const [fruit, description] of fruitsMap) {
console.log(`${fruit}: ${description}`);
}

Output

2. Given an array of numbers, create a Set called uniqueNumbers to store unique numbers.

The task is to to create a JavaScript program that takes an array of numbers and uses a Set to store unique numbers.
1. Create a Set:
Use the Set object in JavaScript to create a set called uniqueNumbers.
2. Add Numbers to the Set:
Iterate through the array of numbers and add each number to the set. The Set automatically ensures that unique values are stored.

Here’s an example program:

// Step 1: Create a Set called uniqueNumbers
const uniqueNumbers = new Set();

// Step 2: Add Numbers to the Set
const numbersArray = [5, 10, 15, 10, 20, 5, 25, 30, 15];

// Iterate through the array and add each number to the set
numbersArray.forEach(number => {
uniqueNumbers.add(number);
});

// Display the unique numbers
console.log(“Unique numbers in the array:”);
console.log(Array.from(uniqueNumbers));

Output

3. Write a JS program to Set a Map Object Using a Set Object in JS. For Example, create a Map Object Name called Vegetables and Add the Different Name of Fruits as a Key with Different Values using the set Object Method and also Proint the value Of different values of the Key using the Get object.

The task is to write a JavaScript program that uses a Set object to set values in a Map object.
1. Create a Set and a Map:
– Use the Set object to store unique values.
– Use the Map object to create a mapping of vegetables.
2. Add Values to the Set and Map:
– Use the Set object to store unique values (in this case, different values associated with a specific vegetable).
– Use the Map object to associate a vegetable name with the Set of values.
3. Print Values of Different Keys:
Use the get method of the Map object to retrieve the Set of values associated with a specific vegetable name.

Here’s an example program:

// Step 1: Create a Set and a Map
const uniqueValuesSet = new Set();
const vegetablesMap = new Map();

// Step 2: Add Values to the Set and Map
// Add values to the set for a specific vegetable
uniqueValuesSet.add(“Green”);
uniqueValuesSet.add(“Nutritious”);

// Set the Map object with the vegetable name as the key and the set of values as the value
vegetablesMap.set(“Broccoli”, uniqueValuesSet);

// Step 3: Print Values of Different Keys
// Use the get method to retrieve the Set of values for a specific vegetable
const broccoliValues = vegetablesMap.get(“Broccoli”);

// Display the values associated with the vegetable
console.log(“Values associated with Broccoli:”);
console.log(Array.from(broccoliValues));

Output

4. Create a Map called fruitPrices with keys as fruit names and values as their respective prices. Add entries for “apple”, “banana”, and “orange”.

The task is to create a JavaScript program that uses a Map object to store prices for different fruits.
1. Create a Map Object:
Use the Map object in JavaScript to create a map called fruitPrices.
2. Add Entries to the Map:
Use the set method of the Map object to add entries, where the keys are different fruit names, and the values are their respective prices.

Here’s an example program:

// Step 1: Create a Map Object called fruitPrices
const fruitPrices = new Map();

// Step 2: Add Entries to the Map
fruitPrices.set(“apple”, 1.5); // Price for an apple
fruitPrices.set(“banana”, 0.8); // Price for a banana
fruitPrices.set(“orange”, 1.2); // Price for an orange

// Display the fruit prices
console.log(“Fruit Prices:”);

// Iterate through the Map entries
for (const [fruit, price] of fruitPrices) {
console.log(`${fruit}: $${price.toFixed(2)}`);
}

Output

5. Given two arrays, one with student names and the other with their corresponding grades, create a Map called studentScores to store each student’s name and grade.

The task is to create a JavaScript program that uses a Map object to store student names and their corresponding grades.
1. Create Two Arrays:
Have two arrays, one for student names and the other for their corresponding grades.
2. Create a Map Object:
Use the Map object in JavaScript to create a map called studentScores.
3. Add Entries to the Map:
Use the set method of the Map object to add entries, where the keys are student names, and the values are their corresponding grades.

Here’s an example program:

// Step 1: Create Arrays for Student Names and Grades
const studentNames = [“Alice”, “Bob”, “Charlie”, “David”];
const studentGrades = [85, 92, 78, 95];

// Step 2: Create a Map Object called studentScores
const studentScores = new Map();

// Step 3: Add Entries to the Map
for (let i = 0; i < studentNames.length; i++) {
studentScores.set(studentNames[i], studentGrades[i]);
}

// Display the student scores
console.log(“Student Scores:”);

// Iterate through the Map entries
for (const [student, grade] of studentScores) {
console.log(`${student}: ${grade}`);
}

Output