Map in Javascript
Map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted.
Syntax:
new Map([it])
Parameter:
- it – It is any iterable object whose values are stored as key, value pair, If the parameter is not specified then a new map created is Empty
Returns: A new Map object
Below is the implementation of Map in javascript:
// map1 contains
// 1 => 2
// 2 => 3
// 4 -> 5
var map1 = new Map([
[1, 2],
[2, 3],
[4, 5]
]);
console.log("Map1");
console.log(map1);
// map2 contains
// firstname => sumit
// lastname => ghosh
// website => w3wiki
var map2 = new Map([
["firstname", "sumit"],
["lastname", "ghosh"],
["website", "w3wiki"]
]);
console.log("Map2");
console.log(map2);
// map3 contains
// Whole number => [1, 2, 3, 4]
// Decimal number => [1.1, 1.2, 1.3, 1.4]
// Negative number => [-1, -2, -3, -4]
var map3 = new Map([
["whole numbers", [1, 2, 3, 4]],
["Decimal numbers", [1.1, 1.2, 1.3, 1.4]],
["negative numbers", [-1, -2, -3, -4]]
]);
console.log("Map3");
console.log(map3);
// map 4 contains
// storing arrays both as key and value
// "first name ", "Last name" => "sumit", "ghosh"
// "friend 1", "sourav" => "friend 2", "gourav"
var map4 = new Map([
[
["first name", "last name"],
["sumit", "ghosh"]
],
[
["friend 1", "friend 2"],
["sourav", "gourav"]
]
]);
console.log("Map4");
console.log(map4);
Output
Map1 Map(3) { 1 => 2, 2 => 3, 4 => 5 } Map2 Map(3) { 'firstname' => 'sumit', 'lastname' => 'ghosh', 'website' => 'w3wiki' } Map3 Map(3) { 'whole numbers' => [ 1, 2, 3, 4 ], 'Decimal numbers' => [ 1.1, 1.2, 1.3, 1.4 ], 'negative numbers' => [ -1, -2, -3, -4 ] } Map4 Map(2) { [ 'first name', 'last name' ] => [ 'sumit', 'ghosh' ], [ 'friend 1', 'friend 2' ] => [ 'sourav', 'gourav' ] }
Learn Data Structures with Javascript | DSA using JavaScript Tutorial
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language, and might be your first preference for Client-side as well as Server-side developments. But have you thought about using Javascript for DSA? Learning Data Structures and Algorithms can be difficult when combined with Javascript. For this reason, we have brought to you this detailed DSA tutorial on how to get started with Data Structures with Javascript from scratch.
Table of Content
- What is Data Structure?
- How to start learning Data Structures with Javascript?
- Learn about Complexities
- Learn Data Structures with JavaScript
- Array in javascript
- String in javascript
- Linked List in Javascript
- Stack in Javascript
- Queue in Javascript
- Tree in Javascript
- Priority Queue in Javascript
- Map in Javascript
- Set in Javascript
- Graph in Javascript
Contact Us