You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Set is a data structure that is perfect if you want to store unique values; it can tell you if it contains a value or not
/*** Sets ***/// create new Set; pass in any Iterable as argumentconstids=newSet([1,2,3]);consthasValue=ids.has(1);// trueids.add(2);// already exists, so no new one is addedids.delete(3)// returns false/true if value was deleted or not since does nothing if value does NOT existfor(constentryofids.values()){console.log(entry);}/*** Maps ***/// create new Map that uses object as a key and attaches additional information in the value of any kind of dataconstperson1={name: 'Matchu'};constperson2={name: 'Pitchu'};constpersonData=newMap([[person1,{age: 30}]]);// get value of key value pairpersonData.get(person1);// { age: 30 }// add new datapersonData.set(person2,{age: 20});for(constentryofpersonData.entries()){console.log(entry);// logs always array of 2 items, the key and the value}for(const[key,value]ofpersonData.entries()){console.log(key,value);}for(constkeyofpersonData.keys()){console.log(key);}for(constvalueofpersonData.values()){console.log(value);}
Maps vs. Objects
Maps
can use ANY values (and types) as keys
better performance for large quantities of data
better performance when adding + removing data frequently
Objects
only may use strings, numbers or symbols as keys
perfect for small/medium-sized sets of data
easier and quicker to create (typically also with better performance)
WeakSets
created with new WeakSet()
only provides methods add, delete, has
WeakSet allows garbage collection of stored e.g. objects, as long as no other part of your code uses this same object -> would not be garbage collected in a normal Set
WeakMaps
similar idea with garbage collection as for WeakSet
created with new WeakMap()
only provides methods get, has, delete, set
Example with Map in React
keeping track of selected items (-> checkboxes) of user
user clicks: add item to Set or remove item from Set