Software Development Exam  >  Software Development Notes  >  JavaScript for Web Development  >  Sets and Maps in JavaScript

Sets and Maps in JavaScript | JavaScript for Web Development - Software Development PDF Download

Introduction

In JavaScript, sets and maps are powerful data structures that allow you to store and manipulate collections of values. They provide efficient ways to handle unique values and key-value pairs, respectively. In this article, we'll explore sets and maps in JavaScript, covering their features, usage, and providing plenty of examples along the way.

Sets in JavaScript

Sets are collections of unique values, where each value can occur only once. Here's how you can work with sets in JavaScript:

Creating a Set
To create a set, you can use the Set constructor or the new Set() syntax:

const set1 = new Set(); // empty set

const set2 = new Set([1, 2, 3, 4, 4]); // set with initial values

Adding and Removing Elements
To add an element to a set, use the add() method. To remove an element, use the delete() method:

const set = new Set();

set.add(1);

set.add(2);

set.add(3);

set.delete(2);

Checking for Element Existence
To check if an element exists in a set, you can use the has() method, which returns a boolean value:

const set = new Set([1, 2, 3]);

console.log(set.has(2)); // Output: true

Iterating Over a Set
To iterate over the elements of a set, you can use the for...of loop:

const set = new Set([1, 2, 3]);

for (const element of set) {

  console.log(element);

}

Set Operations
Sets in JavaScript also support various operations such as union, intersection, and difference. Although these operations are not built-in, you can implement them using set methods and the Set constructor:

const set1 = new Set([1, 2, 3]);

const set2 = new Set([3, 4, 5]);


// Union

const union = new Set([...set1, ...set2]);

console.log(union); // Output: Set { 1, 2, 3, 4, 5 }


// Intersection

const intersection = new Set([...set1].filter(x => set2.has(x)));

console.log(intersection); // Output: Set { 3 }


// Difference

const difference = new Set([...set1].filter(x => !set2.has(x)));

console.log(difference); // Output: Set { 1, 2 }

Maps in JavaScript

Maps are collections of key-value pairs, where each key can be associated with a value. Here's how you can work with maps in JavaScript:

Creating a Map
To create a map, you can use the Map constructor or the new Map() syntax:

const map1 = new Map(); // empty map

const map2 = new Map([['key1', 'value1'], ['key2', 'value2']]); // map with initial key-value pairs

Adding and Retrieving Key-Value Pairs
To add a key-value pair to a map, use the set() method. To retrieve a value based on a key, use the get() method:

const map = new Map();

map.set('name', 'John');

map.set('age', 25);

console.log(map.get('name')); // Output: John

Checking for Key Existence
To check if a key exists in a map, you can use the has() method, which returns a boolean value:

const map = new Map([['name', 'John'], ['age', 25]]);

console.log(map.has('age')); // Output: true

Iterating Over a Map
To iterate over the key-value pairs of a map, you can use the for...of loop:

const map = new Map([['name', 'John'], ['age', 25]]);

for (const [key, value] of map) {

  console.log(`${key}: ${value}`);

}

Map Operations
Maps in JavaScript also support various operations such as size calculation, key removal, and clearing the map:

const map = new Map([['name', 'John'], ['age', 25]]);


console.log(map.size); // Output: 2


map.delete('age');

console.log(map); // Output: Map { 'name' => 'John' }


map.clear();

console.log(map); // Output: Map {}

Sample Problems with Solutions

Problem 1: Write a function to remove duplicate elements from an array using a set.

function removeDuplicates(arr) {

  return [...new Set(arr)];

}


const array = [1, 2, 2, 3, 4, 4, 5];

console.log(removeDuplicates(array)); // Output: [1, 2, 3, 4, 5]

Problem 2: Given an array of numbers, find the first repeating element.

function findFirstRepeating(arr) {

  const set = new Set();

  for (const num of arr) {

    if (set.has(num)) {

      return num;

    }

    set.add(num);

  }

  return undefined;

}


const array = [1, 2, 3, 4, 2, 5, 6];

console.log(findFirstRepeating(array)); // Output: 2

Problem 3: Count the frequency of characters in a string using a map.

function countCharacterFrequency(str) {

  const map = new Map();

  for (const char of str) {

    if (map.has(char)) {

      map.set(char, map.get(char) + 1);

    } else {

      map.set(char, 1);

    }

  }

  return map;

}


const string = 'hello';

console.log(countCharacterFrequency(string));

// Output: Map { 'h' => 1, 'e' => 1, 'l' => 2, 'o' => 1 }

Conclusion

In this article, we covered sets and maps in JavaScript. Sets allow you to work with collections of unique values, while maps enable you to store key-value pairs. By understanding how to create, modify, and iterate over sets and maps, you can leverage their power in your JavaScript programs. Additionally, we solved some sample problems to demonstrate practical applications. With this knowledge, you are now equipped to use sets and maps effectively in your JavaScript projects.

The document Sets and Maps in JavaScript | JavaScript for Web Development - Software Development is a part of the Software Development Course JavaScript for Web Development.
All you need of Software Development at this link: Software Development
51 videos|28 docs|12 tests

Top Courses for Software Development

51 videos|28 docs|12 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Free

,

past year papers

,

Sample Paper

,

ppt

,

Sets and Maps in JavaScript | JavaScript for Web Development - Software Development

,

Sets and Maps in JavaScript | JavaScript for Web Development - Software Development

,

Previous Year Questions with Solutions

,

Objective type Questions

,

shortcuts and tricks

,

Summary

,

study material

,

MCQs

,

Extra Questions

,

mock tests for examination

,

Semester Notes

,

Exam

,

practice quizzes

,

Sets and Maps in JavaScript | JavaScript for Web Development - Software Development

,

Important questions

,

pdf

,

video lectures

,

Viva Questions

;