JavaScript Basics: Map and Set Usage
Curiosity or Inquiry: What are Map and Set objects? #datastructures
Welcome to the Baby Steps Series in JavaScript Basics with Toni! Let this blog entry be your placeholder to quickly reference the usage of Map and Set in JavaScript, with a better understanding of data structures.
Data structures, in any programming language, are the building blocks need to store (data input/receive), process, maintain, and retrieve data.
Data in JavaScript’s arrays and objects:
- JS data types: String, Number, Boolean, Null, Undefined
//arrays []
//objects {} JavaScript objects is denoted by the {} curly brackets
Object values are seen as key/value pairs that can be taken either as properties of the object or methods(functions). Properties are features or attributes of the Object, whereas methods are functions or actions that can be performed on the Object. — Chris Nwamba
Map is a collection of ordered key/value pairs. A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries.
const myMap = new Map();myMap.set('a', 5);
myMap.set('b', 2);
myMap.set('c', 3);
myMap.get('a'); // 5
myMap.set('a', 'ok');
myMap.get('a'); // 'ok'
myMap.size; // 3
myMap.delete('b'); // removes b key/value
myMap.clear() // empties map
Set is a collection of unique values, such as removing duplications from an array, which works! In a Set object, we have access to methods of, has, get, delete, clear, and size, as well as, chaining methods by (.) dot notation. Sets are great in algorithm challenges to set, get and check the boolean with has. Set’s are not Array’s because there is no ordering since arrays are ordered lists.
//declare the Set
const mySet = new Set()//Convert Set to Array
const myArray = Array.from(mySet);//can chain the values with .add and .delete/.clear
const mySet = new Set();
//option 1
mySet.add(1).add(2).delete(1)
//option 2
mySet.add(1)
mySet.add(2)
mySet.delete(1)
mySet.has(1); //false
mySet.clear(); //empties set//remove duplicates
const arr = [1, 1, 1, 2, 3, 4, 5]
const unique = [...new Set(arr)]
// unique = [1, 2, 3, 4, 5]
The Resource section (below), contains information that is highlighted in this blog. Remembering, that it is fine to Google how to use objects, arrays, maps, and sets when dealing with data structures and their data types, in JavaScript. If this helps, take what applies to your chosen programming language(s), then let the rest fly. Per your mental capacity to understand the significance of Map and Set.
Resource:
https://www.better.dev/objects-and-arrays
https://medium.com/geekculture/should-you-use-javascript-maps-and-sets-1660647b55da
https://www.taniarascia.com/understanding-map-and-set-javascript/