How to create a map data structure in JavaScript?

JavaScript ES6 introduced two new data structures – maps and sets. These works similar to objects and arrays. Let’s see how to create a map data structure.

Map Data structure

A map is an ordered collection of key-value pairs. Maps are like objects. However, unlike objects maps are ordered and their keys need not be of string data type. They can be of any data type. Since it is ordered they can be iterable like arrays. Let’s see the syntax to create a map data structure.

Syntax:

let map = new Map([iterable])

let map = new Map()

Properties:

Map.prototype.size – returns the number of key-value pairs in Map object

Syntax:

Map.size

Methods:
  • set() – add/update a key value entry
  • get() – returns a value mapped to a specified key
  • has() – returns a Boolean indicating if a specific key exists or not
  • forEach() – executes a provided function for each key value pair
  • keys() – returns a new iterator object that contains the key of each element
  • values() – returns a new iterator object that contains the value of each element
  • entries() – returns a new iterator object that contains the [key, value] pairs of each element
  • delete() – removes specified elements from object map
  • clear() – removes all elements from object map

Now let us see some of the above methods properties with example.

let emp = new Map();
//set
emp.set('Name','John');
emp.set('ID','101');
emp.set('Salary','10000');
//get
emp.get('Name');
//size
console.log(emp.size);
//has
console.log(emp.has('ID'));
//keys
for (let key of emp.keys()) {
  console.log(key);
}
//values
for (let value of emp.values()) {
  console.log(value);
}
//entries
for (let entry of emp.entries()) {
  console.log(entry);
}
//delete
console.log(emp.delete('Salary')); 
console.log(emp.has('Salary')); 
//clear
console.log(emp.size) 
emp.clear();
console.log(emp.size) 
Output:
How to convert object to map?

To create a map from object we can convert the object into an array of [key, value] pairs and then create a map using it.

Object.entries() – used to convert object to map.

let obj = {
    "Name" : "John",
    "ID" : "101";
    "Salary" : "10000"
}
let newarr = Object.entries(obj);
let map = new Map(newarr);
console.log(map);
How to convert map to object?

Here we use object.fromEntries() to convert a map to object.

const map = new Map([['Name','John'],['ID','101'],['Salary','10000']]);
consr obj = Object.fromEntries(map);
console.log(obj);
Output:

To know more about javascript data structures click here!

Array Data Structure – What you should know?

Already in previous post we have seen about the Data Strucutres in JavaScript. Now we will jump into the creation and implementation of arrays.

As you already know, array represents collection of similar data items. It is an object that stores multiple data items.

 Array Declaration:

By array literal

Simplest way to create an array is by using array literal [ ].

Syntax:

               let arrayname = [value1, value2, value3,….]

By new keyword
Syntax:

               let arrayname = new Array();

//creates an array with 6 elements using array literal
var arr1 = [2,3,1,4,5,7];
//create array using new keyword
var arr2 = new Array(1,3,5,7,9,0);
//create an array with undefined elements
var arr3 = new Array();
//provide elements in arr3
arr3[0] = "Apple";
arr3[1] = "Orange";
arr3[2] = "Banana";
//create an array with 2 elements
var arr4 = new Array("Tom","Paul");
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
Output:
Accessing arrays:

Elements of an array are accessed using indexes.

var arr1 = [2,3,1,4,5,7];
//first element
console.log(arr1[0]);
//fourth element
console.log(arr1[3]);
Output:

2

4

Adding elements to an array:

We use push() and unshift( ) methods to add elements to an array.

push() method adds elements to the end of an array.

unshift() method adds elements to the start of an array.

let fruits = ["apple","orange"];
//using push() method
fruits.push("banana");
//using unshift() method
fruits.unshift("grapes");
console.log(fruits);
Output:

Now what will happen to the above array fruits if we try to add an element at index 5 rather than index 4?

Let’s see,

let fruits = ["grapes","apple","orange","banana"];
//add element at index 5
fruits[5]="strawberry";
console.log(fruits);
Output:

So index 4 will be undefined.

Remove an element from an array:

Here also we can remove from start or end using pop() and shift() methods.

pop() removes the last element

shift() removes the first element

let fruits = ["grapes","apple","orange","banana"];
//pop() method
frutis.pop();
console.log(fruits);
//shift() method
console.log(fruits);
Output:
How to find the length of an array?

It is done by length property. Returns the number of elements in an array.

let fruits = ["grapes","apple","orange","banana"];
console.log(fruits.length);
Output:

4

Methods in an array data structure:

In JavaScript arrays there are various methods available.

MethodsDescription
concat()joins two or more arrays and returns a result
indexOf()searches an element of an array and returns its position
find()returns the first value of an array element that passes a test
findIndex()returns the first index of an array element that passes a test
forEach()calls a function for each element
includes()checks if an array contains a specified element
push()adds a new element to the end of an array and returns the new length of an array
unshift()adds a new element to the beginning of an array and returns the new length of an array
pop()removes the last element of an array and returns the removed element
shift()removes the first element of an array and returns the removed element
sort()sorts the elements alphabetically in strings and in ascending order
slice()selects the part of an array and returns the new array
splice()removes or replaces existing elements and/or adds new elements
let fruits = ["grapes","apple","orange","banana"];
//sort in alphabetical order
fruits.sort();
console.log(fruits);
//find the index position
const pos = fruits.indexOf("apple");
console.log(pos);
//slicing array
const frutis1 = fruits.slice(2)
console.log(fruits1);
//concat two arrays
const frutis2 = frutis.concat(fruits1);
Output:

7 Data Structures in JavaScript you need to know.

In this article, let’s try to understand the important data structures in javascript.

What is a Data Structure?

Data Structure is a storage that is used to store and organize data. It is a way of storing and organizing the data in such a way that it can be accessed more efficiently. It refers to group of data values, the relationship between them and the operations that can be performed on it. JavaScript has dynamic arrays i.e their size and type are not determined.

Now let us jump into the data structures in javascript.

1.Array Data Structure

Most popular linear data structure. All the elements are of same data type and stored in contiguous memory location. An array is represented by set of elements with index.

2.Stack Data Structure

Stack works on Last in First out(LIFO) principle. It is a linear data structure. It contains only one pointer and that points to the top element or last added element of the stack. Whenever we add or delete an element it is added or deleted from the top. Like a pile of books.

3.Queue Data Structure

Queue works on the principle of First in First out(FIFO). It is a linear data structure. It contains two-pointers front pointer and rear pointer. The front pointer contains address of the starting element and rear pointer contains address of the last element. The two main methods used for implementation. Enqueue is process of adding an element in the queue and dequeue is process of removing an element from the queue.

4.Linked List

Linked list is a linear data structure and here unlike arrays elements are stored in non-contiguous memory locations. It is made of group of nodes. Each node has its own data and address to the next node.

Here in linked list you have to start from head and work through the way to desired element. First element is head and last element is tail.

  • List don’t have indexes, so we cannot access elements randomly.
  • Insertion and deletion is more efficient we have to just redirect the pointers.

5.Trees

Tree is a non-linear data structure which consists of nodes connected by edges. This data structure link nodes via parent/child relationship. The top node is called root node and all the other nodes come off that node are called children. The nodes at the bottom of the tree are called leaf nodes. The height of the tree is determined by number of parent/child relationships it has.

Points to note:
  • A connection is valid between nodes when it is from parent to child.
  • Connection between siblings or child to parent are not valid.
  • Tree must have only one root node.
Examples:
  • File folders in our operating system
  • DOM model
Popular Tree based data structure
  • Binary Tree
  • Binary Search Tree
  • AVL Tree
  • Red-Black Tree
  • N-ary Tree
  • 2-3 Tree

6.Graph Data Structure

Graphs are relation based data structure helpful in storing web-like or network relationships. It is made up of a finite collection of nodes called vertices, and the connections between them are known as edges. Graphs can be of two types: Directed graph and undirected graph.

Often used in Social networks, geolocalization(Google maps) and Web analytics.

7.Hash table

Hash table is also known as hash map or hash. Generally used in Object data structures, map or dictionary as it queries through a key and hash function. Hashing is a technique of mapping keys, values into the hash table using a hash function. Key is a searched string and value is the data paired with the key. Insertion and search function are very fast irrespective of the size of the table. Hash tables are built using arrays. In real life example of hash table is in schools each student is assigned a unique id number.

Getting started with JSON in JavaScript

JSON is an acronym of JavaScript Object Notation. It is a storage format derived from JavaScript programming language and it is language independent.It is a text-based data format that is used to store and transfer data. It’s quite important to know while data which we fetch from external API are always in JSON format.

  • It can transport the data from server to client, client to server and server to server.
  • It can generate and store data from user input.
  • It can also build and verify data

JSON Syntax:

JSON objects are in a .json file which is quite similar to object literal syntax which consists of name, value pairs but the format is text only. Both the name and values are quoted in double quotation.

Points to remember:

  • Data is in name/value pair.
  • Curly braces hold objects.
  • Square brackets hold arrays.
  • Data is separated by commas.

If JSON objects are in .js or .html file then the syntax is

In terms of Syntax JSON is similar to JavaScript objects but the name in JavaScript objects are not in double quotes.

JSON Data:

JSON data is written as name and a value pairs. A name/value pair is like field name in double quotes followed by colon (:), then value.

JSON Objects:

As mentioned earlier JSON objects are in curly braces.

JSON Arrays:

JSON arrays are in square brackets.

Here ‘names’ is an array, and it contains 3 objects. Each object is a record of a person.

Accessing JSON Data:

JSON data can be accessed using dot (.) notation.

Output:
Anna
Mills

We can also use square brackets to access JSON data.

JSON vs JavaScript Objects:

JSONJavaScript Objects
The name in name/value pair should be in double quotesThe name can be without double quotes
JSON cannot contain functionsJavaScript objects can contain functions
JSON can be created and used by other programming languagesJavaScript objects can only be used in JavaScript.

Converting JSON to JavaScript Object:

You can convert JSON data to JavaScript object using in-built JSON.parse() function.

Output:

Converting JavaScript object to JSON:

You can convert JavaScript object to JSON using in-built JSON.stringify().

Output:

Keypoints to note:

  • JSON syntax is like Object literal where both name-value pair is in inverted commas.
  • JSON.stringify() Object to JSON
  • JSON.parse() JSON to Object