Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Set and Map Data Structures in ES6

Tech May 8 3

Set Data Sturcture

A Set is similar to an array but automatically removes duplicate values.

Key methods:

  • add
  • size
  • has
  • delete
  • clear
const numberSet = new Set([1,1,2,2,3,3]);
console.log(numberSet); // Set {1, 2, 3}
console.log(numberSet.size); // 3

numberSet.add(4).add(5);
console.log(numberSet.has(4)); // true
console.log(numberSet.delete(4)); // true
numberSet.clear();

Iteration Methods

const colors = new Set(['red', 'green', 'blue']);

// Keys and values are identical in Sets
for (const color of colors.keys()) {
  console.log(color);
}

colors.forEach((value, key) => {
  console.log(key, value);
});

Advanced Deduplicasion

function removeDuplicates(arr) {
  const seen = new Set();
  return arr.filter(item => {
    const identifier = JSON.stringify(item);
    return seen.has(identifier) ? false : seen.add(identifier);
  });
}

Map Data Srtucture

Maps store key-value pairs where keys can be any data type.

const userMap = new Map([
  ['name', 'Alex'],
  ['age', 30],
  [{'id': 1}, 'Admin']
]);

Key methods:

  • set
  • get
  • has
  • delete
  • clear
userMap.set('role', 'Developer');
console.log(userMap.get('age')); // 30
console.log(userMap.has('name')); // true
userMap.delete('name');
userMap.clear();

Iteration Methods

for (const key of userMap.keys()) {
  console.log(key);
}

for (const [key, value] of userMap.entries()) {
  console.log(key, value);
}

userMap.forEach((value, key) => {
  console.log(key, value);
});

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.