Day 10. Sets and Maps

On Day 10, I learned about Set, Map, and the methods for each objects. The jobs those methods do are similar to what I’ve learned before at array or string, but their names and where they’re used is different. Let’s be sure to distinguish those various methods!

header image TIL

Set

Set is a collection of elements. Set can only contain unique values of any type.

1. Creating an empty set

const companies = new Set();
console.log(companies);  // {}
// Set(0) {size: 0}


2. Creating a Set from array

The overlapping elements will be removed.

const languages = [
  'English',
  'Finnish',
  'English',
  'French',
  'Spanish',
  'English',
  'French'
]

const setOfLanguages = new Set(languages);
console.log(setOfLanguages);
// Set(4) {'English', 'Finnish', 'French', 'Spanish'}


Set is an iterable object, so I can iterate through each elements.

const languages = [
  'English',
  'Finnish',
  'English',
  'French',
  'Spanish',
  'English',
  'French'
]

const setOfLanguages = new Set(languages);

for (const language of setOfLanguages) {
  console.log(language);
}
/*
  English
  Finnish
  French
  Spanish
*/


3. Adding an element to a Set

setName.add(value)

The add() method returns the Set object with added value.

// create an empty set
const companies = new Set();
console.log(companies.size)  // 0

// add element to the set
companies.add('Google');
companies.add('Facebook');
companies.add('Amazon');
companies.add('Oracle');
companies.add('Microsoft');

console.log(companies.size);  // 5
console.log(companies);
// Set(5) {'Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft'}


I can chain the add() method multiple times.

const companies = new Set() 
companies.add('Google')
         .add('Facebook')
         .add('Amazon')
         .add('Oracle')
         .add('Microsoft');

console.log(companies);
// Set(5) {'Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft'}


I can also use a loop to add element to a set.

const companies = ['Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft'];
setOfCompanies = new Set();
for (const company of companies) {
  setOfCompanies.add(company);
}

console.log(companies);
// Set(5) {'Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft'}


4. Deleting an element from a Set

  • Read through:

Stackoverflow: How to remove a property from an object

setName.delete(value)

The delete() method removes a specified value from a Set object, if it is in the set. It returns true if value was already in Set; otherwise false.

console.log(companies.delete('Google'));  // true

console.log(companies.size);  // 4
console.log(companies);
// Set(4) {'Facebook', 'Amazon', 'Oracle', 'Microsoft'}


5. Checking an element in the Set

setName.has(value)

The has() method returns a boolean value indicating whether a certain element exists in a set.

console.log(companies.has('Apple')); // false
console.log(companies.has('Facebook')); // true


6. Clearing the Set

setName.clear()

The clear() method removes all elements from a Set object. It returns undefined.

companies.clear();

console.log(countries);  // Set(0) {size: 0}


+ More examples on using Set

const languages = [
  'English',
  'Finnish',
  'English',
  'French',
  'Spanish',
  'English',
  'French'
]
const langSet = new Set(languages);
console.log(langSet.size);  // 4
console.log(langSet);  // Set(4) {'English', 'Finnish', 'French', 'Spanish'}


const counts = [];
const count = {};

for (const l of langSet) {
  const filteredLang = languages.filter((lng) => lng === l);
  counts.push({ lang : l, count: filteredLang.length });
}
console.log(counts);
/* [ 
  {lang: 'English', count: 3},
  {lang: 'Finnish', count: 1},
  {lang: 'French', count: 2},
  {lang: 'Spanish', count: 1}
] */


Set could also be used in counting unique item in an array.

const numbers = [5, 2, 7, 8, 5, 8, 3, 2, 7];
const setOfNumbers = new Set(numbers);

console.log(setOfNumbers);
// Set(5) {5, 2, 7, 8, 3}


7. Union(U) of sets

To find a union, I can use spread operator(...) on two sets.

let a = [1, 2, 3, 4, 5];
let b = [3, 4, 5, 6];
let c = [...a, ...b];
console.log(c);  // (9) [1, 2, 3, 4, 5, 3, 4, 5, 6]

let A = new Set(a);
let B = new Set(b);
let C = new Set(c);
console.log(C);  // Set(6) {1, 2, 3, 4, 5, 6}


8. Intersection(∩) of sets

To find an intersection, I can use filter on two sets. To find the intersection in set A and set B, I should find the values that are both in set A and set B.

let a = [1, 2, 3, 4, 5];
let b = [3, 4, 5, 6];

let A = new Set(a);
let B = new Set(b);

let c = a.filter((num) => B.has(num));
let C = new Set(c);

console.log(C);
// Set(3) {3, 4, 5}

On the upper code, filter() is an array method, and has() is a set method. So, filter() is used on array a, while has() is used on set B. It’s possible because anyway, the intersection would both exist at the array and the set.


9. Difference(\) of sets

To find a difference between two sets, I can use filter. To find the difference in set A and set B, I should find the values that are in set A but not in set B.

let a = [1, 2, 3, 4, 5];
let b = [3, 4, 5, 6];

let A = new Set(a);
let B = new Set(b);

let c = a.filter((num) => !B.has(num));
let C = new Set(c);

console.log(C);
// Set(2) {1, 2}



Map

The Map object holds key-value pairs and remembers the original insertion order of the keys.

1. Creating an empty Map

const map = new Map();
console.log(map);  // Map(0) {}
// Map(0) {size: 0}


2. Creating a Map from array

countries = [
  ['Finland', 'Helsinki'],
  ['Sweden', 'Stockholm'],
  ['Norway', 'Oslo']
]
const map = new Map(countries);
console.log(map.size);  // 3
console.log(map);
// Map(3) {'Finland' => 'Helsinki', 'Sweden' => 'Stockholm', 'Norway' => 'Oslo'}


3. Adding values to the Map

mapName.set(key, value)

The set() method adds or updates an element with a specified key and a value to a Map object. It returns the Map object.

const countriesMap = new Map();
console.log(countriesMap.size);  // 0

countriesMap.set('Finland', 'Helsinki');
countriesMap.set('Sweden', 'Stockholm');
countriesMap.set('Norway', 'Oslo');

console.log(countriesMap.size);  // 3
console.log(countriesMap);
// Map(3) {'Finland' => 'Helsinki', 'Sweden' => 'Stockholm', 'Norway' => 'Oslo'}


Similar to add() method in Set, set() method can also be chained multiple times.

const countriesMap = new Map();
countriesMap.set('Finland', 'Helsinki')
            .set('Sweden', 'Stockholm')
            .set('Norway', 'Oslo');

console.log(countriesMap);
// Map(3) {'Finland' => 'Helsinki', 'Sweden' => 'Stockholm', 'Norway' => 'Oslo'}


4. Getting a value from Map

mapName.get(key)

The get() method returns a specified element from a Map object. It returns the element associated with the specified key, or undefined if the key can’t be found in the Map object.

console.log(countriesMap.get('Finland'));
// Helsinki


5. Checking a key in Map

mapName.has(key)

The has() method returns a boolean indicating whether an element with the specified key exists or not.

console.log(countriesMap.has('Finland'));
// true


Getting all values from Map using loop

A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.

for (const country of countriesMap) {
  console.log(country);
}
/*
  (2) ['Finland', 'Helsinki']
  (2) ['Sweden', 'Stockholm']
  (2) ['Norway', 'Oslo']
*/


for (const [country, city] of countriesMap) {
  console.log(country, city);
}
/*
  Finland Helsinki
  Sweden Stockholm
  Norway Oslo
*/

Leave a comment