JavaScript and TypeScript course ยท Module 3: Classes and OOP

Map and Set

14 min read ยท
In this lesson6

Working on Jurassic Park management systems, we often need to store collections of unique values or map keys to values. In JavaScript, before ES6, we typically used objects or arrays for these purposes, but they came with certain limitations. ECMAScript 6 introduced two new data structures that solve many of these problems: Map and Set.

Set - collections of unique values

Set is a collection of unique values - each value can only appear once. This is an excellent solution when we need to store a set of elements without duplicates.

Creating a new Set

// Creating an empty set
const dinosaurs = new Set();

// Creating a set with initial values
const carnivores = new Set(['Tyrannosaurus', 'Velociraptor', 'Spinosaurus', 'Allosaurus']);

// Creating a set from an array (automatically removes duplicates)
const parkDinosaurs = new Set([
  'Tyrannosaurus',
  'Triceratops',
  'Velociraptor',
  'Stegosaurus',
  'Tyrannosaurus',  // Duplicate - will be skipped
  'Brachiosaurus',
  'Velociraptor'    // Duplicate - will be skipped
]);

console.log(parkDinosaurs.size); // 5 - duplicates were removed
console.log([...parkDinosaurs]); // Convert to array
// ['Tyrannosaurus', 'Triceratops', 'Velociraptor', 'Stegosaurus', 'Brachiosaurus']

Basic Set operations

// Adding elements to the set
dinosaurs.add('Tyrannosaurus');
dinosaurs.add('Velociraptor');
dinosaurs.add('Triceratops');

// Attempting to add a duplicate - will be ignored
dinosaurs.add('Tyrannosaurus');

console.log(dinosaurs.size); // 3

// Checking if an element exists in the set
console.log(dinosaurs.has('Velociraptor')); // true
console.log(dinosaurs.has('Brachiosaurus')); // false

// Removing an element from the set
dinosaurs.delete('Triceratops');
console.log(dinosaurs.size); // 2

// Clearing the entire set
dinosaurs.clear();
console.log(dinosaurs.size); // 0

Iterating over a Set

const dinosaurSpecies = new Set([
  'Tyrannosaurus',
  'Triceratops',
  'Velociraptor',
  'Stegosaurus',
  'Brachiosaurus'
]);

// Iteration using for...of loop
console.log('Dinosaur species in the park:');
for (const species of dinosaurSpecies) {
  console.log(`- ${species}`);
}

// Using forEach method
dinosaurSpecies.forEach(species => {
  console.log(`Species: ${species}`);
});

// Converting Set to array
const speciesArray = [...dinosaurSpecies];
console.log('Array of species:', speciesArray);

// Iteration with access to indices (through array conversion)
[...dinosaurSpecies].forEach((species, index) => {
  console.log(`${index + 1}. ${species}`);
});

Practical uses of Set

1. Removing duplicates from an array

// Array with repeating values
const dinoSightings = [
  'Tyrannosaurus', 'Velociraptor', 'Triceratops', 'Tyrannosaurus',
  'Stegosaurus', 'Velociraptor', 'Brachiosaurus', 'Tyrannosaurus'
];

// Removing duplicates using Set
const uniqueDinoSightings = [...new Set(dinoSightings)];

console.log('Unique species observed in the park:');
console.log(uniqueDinoSightings);
// ['Tyrannosaurus', 'Velociraptor', 'Triceratops', 'Stegosaurus', 'Brachiosaurus']

2. Storing unique dinosaur characteristics

// Cataloging unique dinosaur characteristics
const dinoFeatures = [
  { species: 'Tyrannosaurus', features: ['sharp teeth', 'small arms', 'powerful jaws'] },
  { species: 'Velociraptor', features: ['sharp claws', 'fast runner', 'pack hunter'] },
  { species: 'Triceratops', features: ['three horns', 'neck frill', 'herbivore'] },
  { species: 'Stegosaurus', features: ['back plates', 'tail spikes', 'herbivore'] }
];

// Set of unique features from all dinosaurs
const allFeatures = new Set();

dinoFeatures.forEach(dino => {
  dino.features.forEach(feature => allFeatures.add(feature));
});

console.log('All unique dinosaur features:');
console.log([...allFeatures]);
// ['sharp teeth', 'small arms', 'powerful jaws', 'sharp claws', 'fast runner', 'pack hunter', 'three horns', 'neck frill', 'herbivore', 'back plates', 'tail spikes']

// Counting dinosaurs that are herbivores
const herbivoreCount = dinoFeatures.filter(dino =>
  dino.features.includes('herbivore')
).length;

console.log(`Number of herbivore species: ${herbivoreCount}`); // 2

3. Set operations

We can implement set theory operations such as union, difference, or intersection:

// Dinosaurs in the first enclosure
const paddockA = new Set(['Tyrannosaurus', 'Velociraptor', 'Dilophosaurus']);

// Dinosaurs in the second enclosure
const paddockB = new Set(['Triceratops', 'Stegosaurus', 'Velociraptor', 'Gallimimus']);

// Union - all unique dinosaurs from both enclosures
const allDinosaurs = new Set([...paddockA, ...paddockB]);
console.log('All dinosaurs:', [...allDinosaurs]);
// ['Tyrannosaurus', 'Velociraptor', 'Dilophosaurus', 'Triceratops', 'Stegosaurus', 'Gallimimus']

// Difference - dinosaurs in the first enclosure but not the second
const uniqueToPaddockA = new Set(
  [...paddockA].filter(dino => !paddockB.has(dino))
);
console.log('Dinosaurs unique to paddock A:', [...uniqueToPaddockA]);
// ['Tyrannosaurus', 'Dilophosaurus']

// Intersection - dinosaurs present in both enclosures
const commonDinosaurs = new Set(
  [...paddockA].filter(dino => paddockB.has(dino))
);
console.log('Dinosaurs present in both enclosures:', [...commonDinosaurs]);
// ['Velociraptor']

Map - key-value pair collections

Map is a collection of key-value pairs where keys can be of any type (not just strings, as in plain objects). A Map preserves the order of element insertion and enables easy iteration.

Creating a new Map

// Creating an empty map
const dinoStats = new Map();

// Creating a map with initial key-value pairs
const dinoHeights = new Map([
  ['Tyrannosaurus', 5.6],
  ['Velociraptor', 1.8],
  ['Triceratops', 3.0],
  ['Stegosaurus', 4.0],
  ['Brachiosaurus', 13.0]
]);

console.log(dinoHeights.size); // 5

Basic Map operations

// Adding key-value pairs
dinoStats.set('Tyrannosaurus', { height: 5.6, weight: 7000, diet: 'carnivore' });
dinoStats.set('Velociraptor', { height: 1.8, weight: 15, diet: 'carnivore' });
dinoStats.set('Triceratops', { height: 3.0, weight: 6000, diet: 'herbivore' });

// Getting a value by key
const trexStats = dinoStats.get('Tyrannosaurus');
console.log('T-Rex stats:', trexStats);
// { height: 5.6, weight: 7000, diet: 'carnivore' }

// Checking if a key exists in the map
console.log(dinoStats.has('Velociraptor')); // true
console.log(dinoStats.has('Brachiosaurus')); // false

// Removing an element from the map
dinoStats.delete('Triceratops');
console.log(dinoStats.size); // 2

// Clearing the entire map
// dinoStats.clear();
// console.log(dinoStats.size); // 0

Using different key types

One of the main advantages of Map over plain objects is the ability to use keys of any type:

// Map with different key types
const dinoRecords = new Map();

// Key: string
dinoRecords.set('fastestRunner', 'Gallimimus');

// Key: number
dinoRecords.set(42, 'Number of dinosaurs in the park');

// Key: object
const paddock1 = { id: 'A1', name: 'T-Rex Kingdom' };
dinoRecords.set(paddock1, ['Tyrannosaurus']);

// Key: function
function feedingTime() { return 'Time to feed the dinosaurs!'; }
dinoRecords.set(feedingTime, '09:00 and 17:00');

console.log(dinoRecords.get('fastestRunner')); // 'Gallimimus'
console.log(dinoRecords.get(42)); // 'Number of dinosaurs in the park'
console.log(dinoRecords.get(paddock1)); // ['Tyrannosaurus']
console.log(dinoRecords.get(feedingTime)); // '09:00 and 17:00'

Iterating over a Map

// Map with dinosaur data
const dinosaurData = new Map([
  ['Tyrannosaurus', { diet: 'carnivore', era: 'Late Cretaceous', danger: 5 }],
  ['Velociraptor', { diet: 'carnivore', era: 'Late Cretaceous', danger: 4 }],
  ['Triceratops', { diet: 'herbivore', era: 'Late Cretaceous', danger: 3 }],
  ['Stegosaurus', { diet: 'herbivore', era: 'Late Jurassic', danger: 2 }],
  ['Brachiosaurus', { diet: 'herbivore', era: 'Late Jurassic', danger: 1 }]
]);

// Iterating over key-value pairs
console.log('Dinosaur information:');
for (const [species, info] of dinosaurData) {
  console.log(`${species} - ${info.diet}, danger level: ${info.danger}`);
}

// Iterating only over keys
console.log('Dinosaur species:');
for (const species of dinosaurData.keys()) {
  console.log(`- ${species}`);
}

// Iterating only over values
console.log('Danger levels:');
for (const info of dinosaurData.values()) {
  console.log(`Danger level: ${info.danger}, Diet: ${info.diet}`);
}

// Using forEach method
dinosaurData.forEach((info, species) => {
  console.log(`${species} from ${info.era} era, danger level: ${info.danger}`);
});

Conversions between Map and other structures

// Converting Map to array of key-value pairs
const entriesArray = [...dinosaurData];
console.log('Entries array:', entriesArray);
// [['Tyrannosaurus', {...}], ['Velociraptor', {...}], ...]

// Converting Map to array of keys
const speciesArray = [...dinosaurData.keys()];
console.log('Array of species:', speciesArray);
// ['Tyrannosaurus', 'Velociraptor', 'Triceratops', 'Stegosaurus', 'Brachiosaurus']

// Converting Map to array of values
const infoArray = [...dinosaurData.values()];
console.log('Array of info:', infoArray);
// [{ diet: 'carnivore', era: 'Late Cretaceous', danger: 5 }, ...]

// Converting object to Map
const dinoObject = {
  Ankylosaurus: { weight: 5000, armor: 'high' },
  Parasaurolophus: { weight: 2500, ability: 'vocalization' }
};

const dinoObjectMap = new Map(Object.entries(dinoObject));
console.log('Map from object:', dinoObjectMap);

// Converting Map to object
const herbivores = new Map([
  ['Triceratops', { horns: 3, frill: true }],
  ['Stegosaurus', { backPlates: 17, tailSpikes: 4 }]
]);

const herbivoresObject = Object.fromEntries(herbivores);
console.log('Object from map:', herbivoresObject);
// { Triceratops: { horns: 3, frill: true }, Stegosaurus: { backPlates: 17, tailSpikes: 4 } }

Practical uses of Map

1. Storing data about dinosaur enclosures

// Map for managing dinosaur enclosures
const enclosures = new Map();

// Adding enclosure data
enclosures.set('T-REX-01', {
  dinosaurs: ['Tyrannosaurus'],
  status: 'active',
  securityLevel: 'maximum',
  lastInspection: new Date('2023-06-10')
});

enclosures.set('RAP-02', {
  dinosaurs: ['Velociraptor', 'Velociraptor', 'Velociraptor', 'Velociraptor'],
  status: 'maintenance',
  securityLevel: 'high',
  lastInspection: new Date('2023-06-15')
});

enclosures.set('HERB-03', {
  dinosaurs: ['Triceratops', 'Stegosaurus', 'Parasaurolophus'],
  status: 'active',
  securityLevel: 'medium',
  lastInspection: new Date('2023-06-12')
});

// Function finding all active enclosures
function getActiveEnclosures(enclosuresMap) {
  const active = new Map();

  for (const [id, data] of enclosuresMap) {
    if (data.status === 'active') {
      active.set(id, data);
    }
  }

  return active;
}

const activeEnclosures = getActiveEnclosures(enclosures);
console.log('Active enclosures:', [...activeEnclosures.keys()]);
// ['T-REX-01', 'HERB-03']

// Function finding enclosures needing inspection (last inspection older than 7 days)
function findEnclosuresNeedingInspection(enclosuresMap) {
  const today = new Date();
  const sevenDaysAgo = new Date(today);
  sevenDaysAgo.setDate(today.getDate() - 7);

  return [...enclosuresMap].filter(([_, data]) =>
    data.lastInspection < sevenDaysAgo
  ).map(([id]) => id);
}

// Note: in a real example, dates would be more than a few days apart
console.log('Enclosures needing inspection:', findEnclosuresNeedingInspection(enclosures));

2. Tracking dinosaur statuses

// Map for tracking dinosaur statuses
const dinosaurStatuses = new Map();

// Adding and updating statuses
function updateDinosaurStatus(id, status) {
  const currentTime = new Date();

  if (dinosaurStatuses.has(id)) {
    const currentStatus = dinosaurStatuses.get(id);

    // Keep status history
    currentStatus.history.push({
      status: currentStatus.current,
      time: currentStatus.updatedAt
    });

    // Update status
    currentStatus.current = status;
    currentStatus.updatedAt = currentTime;

    dinosaurStatuses.set(id, currentStatus);
  } else {
    // New entry for dinosaur
    dinosaurStatuses.set(id, {
      current: status,
      updatedAt: currentTime,
      history: []
    });
  }

  return `Dinosaur ${id} status updated to: ${status}`;
}

// Using the function to track statuses
console.log(updateDinosaurStatus('T-REX-001', 'feeding'));
console.log(updateDinosaurStatus('V-RAP-004', 'resting'));

// Later we update the status
setTimeout(() => {
  console.log(updateDinosaurStatus('T-REX-001', 'hunting'));
  console.log(updateDinosaurStatus('V-RAP-004', 'active'));

  // Displaying status history
  console.log('T-REX-001 status history:', dinosaurStatuses.get('T-REX-001'));
}, 1000);

3. Storing relationships between entities (dinosaur kinship graph)

// Map representing dinosaur kinship graph
const dinoRelationships = new Map();

// Adding dinosaurs and their relationships
dinoRelationships.set('Blue', ['Delta', 'Echo', 'Charlie']); // Velociraptor and its siblings
dinoRelationships.set('Delta', ['Blue', 'Echo', 'Charlie']);
dinoRelationships.set('Echo', ['Blue', 'Delta', 'Charlie']);
dinoRelationships.set('Charlie', ['Blue', 'Delta', 'Echo']);

dinoRelationships.set('Rexy', ['Junior']); // T-Rex and its offspring
dinoRelationships.set('Junior', ['Rexy']);

// Function finding all related dinosaurs (network)
function findRelatedDinosaurs(name, relationshipsMap) {
  const visited = new Set();
  const toVisit = [name];

  while (toVisit.length > 0) {
    const current = toVisit.pop();

    if (!visited.has(current)) {
      visited.add(current);

      // Add related dinosaurs to visit
      const related = relationshipsMap.get(current) || [];
      toVisit.push(...related);
    }
  }

  // Remove the original dinosaur from results
  visited.delete(name);

  return [...visited];
}

console.log('Dinosaurs related to Blue:', findRelatedDinosaurs('Blue', dinoRelationships));
// ['Charlie', 'Echo', 'Delta']

console.log('Dinosaurs related to Rexy:', findRelatedDinosaurs('Rexy', dinoRelationships));
// ['Junior']

Comparison of Map and objects, Set and arrays

Map vs. Object

FeatureMapObject
KeysAny typeOnly strings and symbols
Size.size propertyRequires Object.keys(obj).length
IterationBuilt-in methods and interfaceRequires additional methods
OrderPreserves insertion orderImplementation-dependent (undefined before ES2015)
Default keysNoneInherits from prototype
PerformanceBetter for frequent add/removeBetter for simple cases

When to use Map:

  • When keys are not strings
  • When order of elements matters
  • When you frequently add and remove key-value pairs
  • When you need to easily iterate over the collection
  • When you need to know the number of elements

When to use objects:

  • When keys are simple strings
  • When you need JSON.stringify()
  • When you need access to the prototype and methods
  • For simple data structures

Set vs. Array

FeatureSetArray
Unique valuesAutomatic duplicate removalCan contain duplicates
Element accessOnly through iterationDirect by index
OperationsAdd/remove/check in O(1) timePresence check in O(n) time
OrderPreserves insertion orderIndexed, preserves order
ManipulationBasic methodsRich API with many methods

When to use Set:

  • When you need to store unique values
  • When you frequently check if a value exists (has)
  • When you need to easily remove duplicates from arrays
  • When performing set operations (union, difference, intersection)

When to use arrays:

  • When order of elements matters
  • When you need access by index
  • When you need to manipulate elements (sort, filter)
  • When duplicates are allowed or desired

Performance of Map and Set

One of the main advantages of Map and Set is their performance. Operations such as adding, removing, and checking presence are performed in constant O(1) time, unlike array operations that may require O(n) time.

// Performance comparison: array vs Set for checking presence

// Creating large collections
const largeArray = [];
const largeSet = new Set();

// Adding many elements
for (let i = 0; i < 1000000; i++) {
  largeArray.push(`item-${i}`);
  largeSet.add(`item-${i}`);
}

// Measuring search time in array
console.time('Array search');
const arrayHasItem = largeArray.includes('item-500000');
console.timeEnd('Array search');

// Measuring search time in Set
console.time('Set search');
const setHasItem = largeSet.has('item-500000');
console.timeEnd('Set search');

console.log(`Array search result: ${arrayHasItem}`);
console.log(`Set search result: ${setHasItem}`);

// Results may vary, but Set should be significantly faster
// Array search: 15ms
// Set search: 0.01ms

Nested structures and complex examples

Map containing Sets

// Map assigning abilities to dinosaurs
const dinosaurAbilities = new Map();

// Adding ability sets for different dinosaurs
dinosaurAbilities.set('Tyrannosaurus', new Set([
  'powerful bite', 'intimidating roar', 'keen sense of smell'
]));

dinosaurAbilities.set('Velociraptor', new Set([
  'speed', 'pack hunting', 'intelligence', 'sharp claws'
]));

dinosaurAbilities.set('Triceratops', new Set([
  'charging', 'defensive horns', 'thick skin'
]));

// Adding new abilities
dinosaurAbilities.get('Tyrannosaurus').add('night vision');

// Checking if a dinosaur has a specific ability
function checkDinosaurAbility(species, ability) {
  if (!dinosaurAbilities.has(species)) {
    return `Unknown dinosaur species: ${species}`;
  }

  const abilities = dinosaurAbilities.get(species);
  if (abilities.has(ability)) {
    return `${species} has the ability: ${ability}`;
  } else {
    return `${species} does not have the ability: ${ability}`;
  }
}

console.log(checkDinosaurAbility('Velociraptor', 'intelligence')); // Has it
console.log(checkDinosaurAbility('Tyrannosaurus', 'flying')); // Does not have it
console.log(checkDinosaurAbility('Brachiosaurus', 'height')); // Unknown species

// Finding dinosaurs with a specific ability
function findDinosaursWithAbility(ability) {
  const result = [];

  for (const [species, abilities] of dinosaurAbilities) {
    if (abilities.has(ability)) {
      result.push(species);
    }
  }

  return result;
}

console.log('Dinosaurs with "intelligence" ability:',
  findDinosaursWithAbility('intelligence')); // ['Velociraptor']

Set containing Maps

// Set of dinosaur reports (each report is a map)
const dinoReports = new Set();

// Creating several reports as Maps
const report1 = new Map([
  ['date', '2023-06-15'],
  ['observer', 'Dr. Grant'],
  ['species', 'Velociraptor'],
  ['count', 3],
  ['behavior', 'hunting'],
  ['location', 'Sector B']
]);

const report2 = new Map([
  ['date', '2023-06-16'],
  ['observer', 'Dr. Sattler'],
  ['species', 'Tyrannosaurus'],
  ['count', 1],
  ['behavior', 'feeding'],
  ['location', 'Sector C']
]);

const report3 = new Map([
  ['date', '2023-06-16'],
  ['observer', 'Dr. Malcolm'],
  ['species', 'Velociraptor'],
  ['count', 2],
  ['behavior', 'resting'],
  ['location', 'Sector D']
]);

// Adding reports to the set
dinoReports.add(report1);
dinoReports.add(report2);
dinoReports.add(report3);

// Searching reports based on criteria
function findReports(reports, criteria) {
  return [...reports].filter(report => {
    for (const [key, value] of Object.entries(criteria)) {
      if (report.get(key) !== value) {
        return false;
      }
    }
    return true;
  });
}

// Finding Velociraptor reports
const raptorReports = findReports(dinoReports, { species: 'Velociraptor' });
console.log('Velociraptor reports:', raptorReports.length);
raptorReports.forEach(report => {
  console.log(`${report.get('date')} - ${report.get('behavior')} - ${report.get('location')}`);
});

// Finding reports from a specific day
const reportsFrom16 = findReports(dinoReports, { date: '2023-06-16' });
console.log('Reports from June 16:', reportsFrom16.length);

Summary

Map and Set are powerful data structures introduced in ES6 that enrich JavaScript's capabilities for organizing and manipulating data:

Set

  • Stores unique values of any type
  • Automatically removes duplicates
  • Offers fast add, delete, and presence check operations
  • Useful for set operations like union, difference, and intersection
  • Ideal solution for removing duplicates from arrays

Map

  • Stores key-value pairs where keys can be of any type
  • Preserves the order of element insertion
  • Offers convenient methods for managing and iterating over data
  • More efficient than objects for frequent add/remove operations
  • No "built-in" keys unlike objects

In the context of our Jurassic Park, these data structures allow us to:

  • Efficiently manage collections of unique dinosaurs and their traits (Set)
  • Create relationships between different park entities like dinosaurs, enclosures, and staff (Map)
  • Better track statuses, history, and other dynamic data (Map)
  • Perform faster search and check operations on large datasets

Skillful use of these structures can significantly improve the performance and readability of code in JavaScript applications.

Code for this lesson: index.js
// Map and Set - Jurassic Park Registry
console.log("=== Map and Set in Jurassic Park ===\n");

// 1. Map - dinosaur registry
const dinoRegistry = new Map();

dinoRegistry.set("DINO-001", { species: "T-Rex", weight: 8000, zone: "A" });
dinoRegistry.set("DINO-002", { species: "Velociraptor", weight: 15, zone: "B" });
dinoRegistry.set("DINO-003", { species: "Triceratops", weight: 6000, zone: "C" });
dinoRegistry.set("DINO-004", { species: "Brachiosaurus", weight: 80000, zone: "D" });
dinoRegistry.set("DINO-005", { species: "Stegosaurus", weight: 5000, zone: "C" });

console.log("--- Map: Dinosaur registry ---");
console.log(`Number of entries: ${dinoRegistry.size}`);

// Reading from the Map
const rex = dinoRegistry.get("DINO-001");
console.log(`DINO-001: ${rex.species} (${rex.weight}kg)`);

// Checking existence
console.log(`Does DINO-003 exist? ${dinoRegistry.has("DINO-003")}`);
console.log(`Does DINO-099 exist? ${dinoRegistry.has("DINO-099")}`);

// 2. Iterating over the Map
console.log("\n--- Iterating over the Map ---");
for (const [id, dino] of dinoRegistry) {
  console.log(`${id}: ${dino.species} - zone ${dino.zone}`);
}

// 3. Map with object keys
const zoneMap = new Map();
const zoneA = { id: "A", name: "Predator Zone" };
const zoneB = { id: "B", name: "Raptor Zone" };

zoneMap.set(zoneA, ["T-Rex", "Allosaurus"]);
zoneMap.set(zoneB, ["Blue", "Charlie", "Delta"]);

console.log("\n--- Map with object keys ---");
console.log(`${zoneA.name}: ${zoneMap.get(zoneA).join(", ")}`);
console.log(`${zoneB.name}: ${zoneMap.get(zoneB).join(", ")}`);

// 4. Set - unique species
const speciesSightings = [
  "T-Rex", "Velociraptor", "T-Rex", "Triceratops",
  "Velociraptor", "Velociraptor", "Stegosaurus",
  "T-Rex", "Brachiosaurus", "Triceratops",
];

const uniqueSpecies = new Set(speciesSightings);

console.log("\n--- Set: Unique species ---");
console.log(`All sightings: ${speciesSightings.length}`);
console.log(`Unique species: ${uniqueSpecies.size}`);
console.log("Species:", [...uniqueSpecies].join(", "));

// 5. Set operations
const morningSpecies = new Set(["T-Rex", "Velociraptor", "Triceratops"]);
const eveningSpecies = new Set(["Velociraptor", "Stegosaurus", "Brachiosaurus"]);

// Union (sum of sets)
const allSpecies = new Set([...morningSpecies, ...eveningSpecies]);
console.log("\n--- Set operations ---");
console.log(`Morning: ${[...morningSpecies].join(", ")}`);
console.log(`Evening: ${[...eveningSpecies].join(", ")}`);
console.log(`All (union): ${[...allSpecies].join(", ")}`);

// Intersection
const commonSpecies = [...morningSpecies].filter(s => eveningSpecies.has(s));
console.log(`Common: ${commonSpecies.join(", ")}`);

// Difference
const morningOnly = [...morningSpecies].filter(s => !eveningSpecies.has(s));
console.log(`Morning only: ${morningOnly.join(", ")}`);

// 6. Set for removing duplicates from data
const dinoAlerts = ["T-Rex alert", "Fence breach", "T-Rex alert", "Power loss", "Fence breach"];
const uniqueAlerts = [...new Set(dinoAlerts)];
console.log(`\nUnique alerts: ${uniqueAlerts.join(", ")}`);

// 7. Converting Map to array
console.log("\n--- Converting the Map ---");
const dinoNames = [...dinoRegistry.values()].map(d => d.species);
console.log(`Names from Map: ${dinoNames.join(", ")}`);
const dinoIds = [...dinoRegistry.keys()];
console.log(`IDs from Map: ${dinoIds.join(", ")}`);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the main advantage of Map over a plain object ({}) as a key-value collection?

  2. 2. Which data collection allows storing only unique values?

Hands-on tasks in the game

  • Code editor

    Use Map and Set for a dinosaur registry and unique species

  • Click in order

    Arrange the elements for iterating over a Map using for...of:

  • Code editor

    Combine arrow functions with destructuring and spread in the park system

  • Vertical ordering

    Arrange the dinosaur class hierarchy from general to specific:

  • Click in order

    Arrange the elements of a super call in an inheriting class:

  • Horizontal ordering

    Arrange the elements of class inheritance:

  • Vertical ordering

    Arrange the execution order when creating a class object:

  • Code editor

    Create a mini park management system using all ES6+ concepts

  • Vertical ordering

    Arrange object creation methods chronologically:

  • Code editor

    Create a variable to store a dinosaur species

  • Code editor

    Write a function to calculate fossil age

  • Horizontal ordering

    Arrange the elements of the spread operator in an array:

  • Vertical ordering

    Arrange the steps for creating a class hierarchy:

  • Click in order

    Arrange the elements of array destructuring

  • Vertical ordering

    Arrange the steps of nested object destructuring:

  • Click in order

    Arrange the elements of object destructuring

  • Horizontal ordering

    Arrange the elements of the spread operator

  1. QuestionAdvantages of Map over Object
  2. Coding taskMap and Set
  3. Click in orderfor...of Syntax with Map
  4. Coding taskES6+ Practice: Arrow Functions
  5. Put in orderES6 Class Hierarchy
  6. Click in ordersuper() Syntax in Constructor
  7. Put in orderClass Syntax with extends
  8. Put in orderConstructor Execution Order
  9. Coding taskES6+ Practice: Complex Project
  10. Put in orderEvolution of Object Creation in JavaScript
  11. Coding taskExercise: Create a Variable to Store a Dinosaur Species
  12. Coding taskExercise: Write a Function to Calculate Fossil Age
  13. Put in orderArray Spread Syntax
  14. Put in orderES6 Class Inheritance Steps
  15. QuestionData Collections in ES6
  16. Click in orderArray Destructuring Syntax
  17. Put in orderNested Destructuring Steps
  18. Click in orderObject Destructuring Syntax
  19. Put in orderSpread Operator Syntax

Useful articles