Javascript – Sets & Maps

Sets and Maps new datasctructures introduced in ES6

Sets

A collection of unique data values (iterrables)

const mySet = new Set([
 'unique value 1', // iterable
 'unique value 2'
]);

Sets are also iterrables like arrays, however they differ for two reasons:

  • Can contain only unique elements
  • Order of elements are irrelevant

If a string (also an iterrable) is passed this will create a set with elements of each letter of the string (must be no duplicate letters though.

Set methods

console.log(mySet.size); // similar to .length
console.log(mySet.has('element'); // similar to .includes
orderSet.add('New Element'):
orderSet.delete('Old Element');
orderSet.clear()

Retrieving values from sets

Cannot be done as there is no point as all elements are unique. Just need to use .has() method

Looping sets

for ( const myDatavalue of mySet ) // action

Use cases for sets

Can be used to create a unique iterrable from an array which has multiple repeating datavalues.

const staff = ['Waiter', 'Chef', 'Waiter', 'Manager', 'Waiter', 'Chef'];
const uniqueStaff = [..new Set(staff)]; // creates an array which only includes waiter, chef and manager

New ES2025 set methods

const commonFoods = italianFoods.intersection(mexicanFoods) // creates a new set of common elements

const italianMexicanFusion = italianFoods.union(mexicanFoods); // Creates a new array combining all elements without duplicates. ( although this can me done with spread operator)

const uniqueItalianFoods = italianFoods.difference(mexicanFoods) // create a set of elements that are included only in Italian Foods

const uniqueItalianAndMexicanFoods = italianFoods.symetricDifference(mexicanFoods) 

.isDisjointFrom() // check if both arrays have unique values from each other

Maps

Maps are like arrays but with assignable keys.

Create with new Map();

// best practice is to create an empty map first
const restaurant = new Map();

Add items with .set()

restaurant.set('name', 'My Lovely Restaurant');
restaurant.set('open', '19').set('closed', '23'); // can also be chained
restaurant.set(true, 'We are open').set(false, 'We are closed'); // can use boolean or numbers too

Retrieve values with .get(key) – expressions can also be passed

console.log(restaurant.get('name')); // returns name value

let time = 21;
console.log(rest.get(time > restaurant.get('open') && time < restaurant.get('close'))); returns true, therefore returns 'we are open' (value of true).

Other map methods

.has()
.delete()
.size
.clear()

Objects and Arrays can also be Map Keys. Arrays must be created in the heap.

Populating maps without using .set() method

const question = new Map([
 ['question', 'What is the capital of Peru?'],
 [1, 'Lima'],
 [2, 'Lama'],
 [3, 'Lemur'],
 ['correct', 1],
 [true, 'Correct'],
 [false, 'Try Again']
]);

Converting objects to map

const myMap = new Map(Object.entries(myObject));

Destructing maps in the same way as destructing objects (although .entries method is not required

for(const [key, value] of myMap) {
 //
}
const answer = Number(
  prompt(
    `What is the capital of Peru\n1. ${question.get(1)}\n2. ${question.get(2)}\n3. ${question.get(3)}`
  )
);
console.log(question.get(answer === question.get('correct')));

Leave a Reply

Your email address will not be published. Required fields are marked *