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
Copy file name to clipboardExpand all lines: 09-Data-Structure-Modern-Operators-and-Strings/README.md
+68Lines changed: 68 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -413,3 +413,71 @@ console.log(uniqueStaff);
413
413
```
414
414
415
415
Sets are not intended to replace arrays at all but only for working with unique values.
416
+
417
+
# Maps
418
+
419
+
Map objects are a collection of key-value pairs. Similar to objects, their keys only occur once and it is unique in a collection.
420
+
421
+
The main difference is that `objects` only support string and `symbol` keys where as Maps supports any key type.
422
+
423
+
Maps are created by defining a new map and to add items to the map, we use the `set()` method, which takes in any key `name` and a value.
424
+
425
+
```js
426
+
constrest=newMap();
427
+
rest.set("name", "Classico Italiano"); // String as key
428
+
rest.set(1, "Firenze, Italy"); // Number as key
429
+
```
430
+
431
+
We can also chain the set method with other items.
432
+
433
+
```js
434
+
rest
435
+
.set(categories, [])
436
+
.set("open", 11)
437
+
.set("close", 23)
438
+
.set(true, "We are open :D")
439
+
.set(false, "We are closed :(");
440
+
441
+
console.log(rest);
442
+
```
443
+
444
+
To get items inside a `Map`, we use the `get()` method, with the key name we want to get. The key name data type also matters.
445
+
446
+
```js
447
+
console.log(rest.get(true));
448
+
449
+
consttime=21;
450
+
console.log(rest.get(time >rest.get("open") && time <rest.get("close")));
451
+
```
452
+
453
+
The rest also contains the `has()` method for checking for elements.
454
+
455
+
```js
456
+
rest.has(categories); // True
457
+
```
458
+
459
+
To remove elements from the Map, we use the delete method.
460
+
461
+
```js
462
+
rest.delete(1);
463
+
```
464
+
465
+
We can also use objects as Map keys
466
+
467
+
```js
468
+
rest.set([1, 2], "Test");
469
+
```
470
+
471
+
However, if we try to use the `get()` method on `[1, 2]`, it will not work because they are not in the same memory. In other to get the value `Test`, we store the element key in a variable and use that variable to get the element.
472
+
473
+
```js
474
+
constarr= [1, 2];
475
+
rest.set(arr, "Test");
476
+
rest.get(rest.get(arr));
477
+
```
478
+
479
+
We an also use the `rest` on `DOM` elements, which allows us to do advanced functionalities.
0 commit comments