Data Structure in Js
Data Structure in Js
Map
Sets
Maps: Maps are collections of keys and values of any type, in simple word Map is a collection
of key-value pairs. It works like an object in JavaScript. It returns a new or empty map.
Syntax: var map = new Map();
Methods Description
It sets the value for the key .It takes two parameters, key and the value for the
map.set() key.
map.has() It checks whether a key is present in the map or not then its returns true.
It takes a value associated with a key .If the value is not available then its
map.get() undefined.
It returns a new iterator array of which contains key-value pair for each
map.entries() element by insertion order.
map.forEach( It executes the callback function once. This function executed for each element
) in the map.
Here's a detailed explanation of the methods for Map:
1. map.size:
o Description: Returns the number of key-value pairs in the map.
o Example:
map.set('name', 'John');
map.set('age', 30);
console.log(map.size); // Output: 2
2. map.set(key, value): Description: Sets a value for a specific key in the map. It takes two
parameters: the key and the value.
Example:
let map = new Map();
3. map.has(key):
o Description: Checks whether a specific key exists in the map. Returns true if the key
is present, otherwise false.
o Example:
map.set('country', 'USA');
4. map.get(key):
o Description: Retrieves the value associated with a specific key. Returns undefined if
the key is not present.
o Example:
map.set('name', 'Alice');
5. map.keys():
o Description: Returns an iterator containing all the keys in the map.
o Example:
6. map.entries():
o Description: Returns an iterator containing key-value pairs for each element in the
map, in insertion order.
o Example:
7. map.values():
o Description: Returns an iterator for all values in the map, in insertion order.
o Example:
8. map.delete(key):
o Description: Removes the entry associated with the specified key from the map.
Returns true if the key existed and was deleted, otherwise false.
o Example:
9. map.clear():
o Description: Removes all key-value pairs from the map.
o Example
map.set('name', 'John');
map.set('age', 25);
map.clear();
console.log(map.size); // Output: 0
10. map.forEach(callback):
o Description: Executes a callback function for each key-value pair in the map. The
callback function takes three arguments: value, key, and the map itself.
o Example:
map.set('name', 'John');
map.set('age', 25);
});
// Output:
// name: John
// age: 25
The map.forEach() method is used to execute a callback function once for each key-value pair in a
Map. It iterates over each element in the Map in the order in which the elements were inserted.
Key Points:
The forEach() method loops over each key-value pair in the Map, calling the provided
callback function.
The callback receives three arguments for each iteration:
1. The value stored in the current entry.
2. The key corresponding to that value.
3. The Map itself (optional; useful if you want to reference the entire Map inside the
callback).
The iteration is done in insertion order. So, the first key-value pair added to the map will be
processed first.
These methods make Map a powerful and flexible data structure for working with key-value
pairs in JavaScript.
map.set('age', 25);
});
console.log(map.get('age')); // Output: 30
2. WeakMap
Features:
Implementation Example:
// Remove a reference
obj1 = null; // obj1 can now be garbage-collected since WeakMap holds a weak reference
Use Case:
WeakMap is ideal when you want to associate metadata with objects without preventing them
from being garbage-collected. This makes it perfect for scenarios such as caching objects or
storing metadata about DOM nodes.
3 What is a Set?
A Set is a collection of unique values in JavaScript, introduced in ES6
(ECMAScript 2015). Unlike arrays, Sets do not allow duplicate values,
which means every value in a Set appears only once.
Key Characteristics of Set:
Uniqueness: No duplicates are allowed.
Mutability: A set is mutable, meaning you can add and remove
elements.
Order of Elements: The elements are ordered based on their
insertion order (just like arrays).
Objects and Primitives: A Set can store both primitive values (like
strings, numbers) and objects.
Methods Description
set.size() It returns the total number of values present in the set.
set.add() It adds a value to the set if the value was not already in
the set.
set.clear() It removes all values from the set
It removes one value from the set, the value is passed as
set.delete(v) argument.
If the passed value “v” is in the set, then this method
set.has(v) returns true.
It returns an iterator object which contains an array
set.entries() having the entries of the set.
set.values() and They both are returns all the values from the Set, similar
set.keys() to map.values().
It same as map.forEach() ,it executes the callback
set.forEach() function once. This function executed for each element in
method the set.
Creating a Set:
Or, you can initialize it with an array (duplicates will automatically be removed):
Methods of Set
1. set.size:
o Description: Returns the total number of unique values present in the Set.
console.log(mySet.size); // Output: 4
2. set.add(value):
o Description: Adds a new value to the Set if it’s not already present. If the value is
already in the Set, it will not be added again.
o Example:
mySet.add(1);
mySet.add(2);
3. set.clear():
o Description: Removes all values from the Set, making it empty.
o Example:
mySet.clear();
console.log(mySet.size); // Output: 0
4. set.delete(value):
o Description: Removes a specific value from the Set. Returns true if the value was
present and deleted, and false otherwise.
o Example:
mySet.delete(2);
5. set.has(value):
o Description: Checks whether a specific value is present in the Set. Returns true if the
value is found, otherwise false.
o Example:
6. set.entries():
o Description: Returns an iterator object containing an array of [value, value] for each
element in the Set (similar to Map.entries()). Since Set doesn’t have keys, both
elements in the array are the same.
o Example:
}
7. set.values() and set.keys():
o Description: Both set.values() and set.keys() return an iterator over the values of the
Set. Since a Set doesn't have keys (like a Map), these two methods are functionally
the same.
o Example:
console.log(value); // Output: 1, 2, 3
8. set.forEach(callback):
o Description: Executes the provided callback function once for each element in the
Set, in the order they were inserted. The callback function receives three arguments:
value: The current value being processed in the Set.
valueAgain: Same as the first argument (because there are no keys in a Set).
set: The entire Set object.
o Example:
mySet.forEach((value) => {
console.log(value);
});
// Output: 1, 2, 3
// Add a value
mySet.add(5);
console.log(mySet.size); // Output: 5
mySet.forEach((value) => {
console.log(value); // Output: 1, 2, 3, 4, 5
});
// Delete a value
mySet.delete(4);
mySet.clear();
console.log(mySet.size); // Output: 0
Summary:
4. WeakSet: A WeakSet is similar to Set, but with some important differences: The elements must
be objects. References to objects in a WeakSet are weak, so if no other references exist to an object, it
can be garbage-collected
A WeakSet in JavaScript is a special type of set that, like a regular Set, holds a collection of unique
values. However, it has some important differences that make it suitable for specific use cases,
especially when memory management and object lifecycle are important.
Features of WeakSet:
Garbage Collection: If an object inside a WeakSet has no other references in the program, it
can be garbage-collected automatically. This makes WeakSet useful for memory management
purposes, as you don't have to manually remove objects from it when they're no longer
needed.
No Duplicates: Like a regular Set, a WeakSet does not allow duplicate objects. If you try to
add the same object twice, it will be stored only once.
Use Cases:
The main use case for WeakSet is when you need to track objects without preventing them from being
garbage-collected. This can be useful in scenarios where objects are temporary or only need to be
remembered while they are in use elsewhere in the program.
WeakSet Methods:
Since a WeakSet cannot be iterated over and does not store primitive values, it has fewer methods
than a regular Set.
1. weakSet.add(value):
o Description: Adds an object to the WeakSet. If the object is already in the set, it is
ignored (i.e., no duplicates).
o Example:
weakSet.add(obj1);
weakSet.add(obj2);
console.log(weakSet)
2. weakSet.has(value):
o Description: Checks if the specified object is in the WeakSet. Returns true if the
object is found, and false otherwise.
o Example:
3. weakSet.delete(value):
o Description: Removes the specified object from the WeakSet. If the object was
successfully removed, it returns true. If the object was not in the set, it returns false.
o Example:
weakSet.delete(obj1);
weakSet.add(obj1);
weakSet.add(obj2);
weakSet.delete(obj2);
The unique feature of WeakSet is that the objects inside it are weakly referenced. This means if there
are no other references to an object stored in the WeakSet, the JavaScript engine will automatically
remove it from memory (garbage collection).
For example:
weakSet.add(obj);
In this code, once obj is set to null, it is no longer referenced by any variable. Because the WeakSet
holds a weak reference to obj, the object is eligible for garbage collection and will be removed from
memory automatically when needed.
A WeakSet is like a Set, but it can only store objects (not primitives), and it holds weak
references to those objects.
If no other part of the program references an object in a WeakSet, that object will be
automatically garbage-collected.
WeakSet does not provide methods to iterate through its contents, nor does it have a size
property, making it less predictable but more memory-efficient in some cases.
WeakSet is particularly useful for memory-sensitive scenarios, where you need to keep track of
objects without preventing them from being garbage-collected.
The JSON format is syntactically similar to the code for creating JavaScript objects. Because of this, a
JavaScript program can easily convert JSON data into JavaScript objects.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
console.log(person);
Characteristics of JSON
Lightweight text-based data interchange format: JSON is simpler to read and write
when compared to XML.
Widely used: JSON is a common format for data storage and communication on the
web.
JSON Objects
A JSON object is a collection of key/value pairs. The keys are strings, and the values can
be strings, numbers, objects, arrays, true, false, or null.
JSON Arrays
A JSON array is an ordered collection of values. The values can be strings, numbers,
objects, arrays, true, false, or null.
Convert a JSON Text to a JavaScript Object
To convert JSON text into a JavaScript object, you can use the JSON.parse() method as
shown in the example above. This method parses the JSON string and constructs the
JavaScript value or object described by the string.
Example: We will be using the JSON.parse() method to convert the JSON text to a
JavaScript Object
'{"carName":"Aura","brandName":"Hyndai" },' +
'{"carName":"Nexon","brandName":"Tata" }]}';
console.log(cars);
const cars=JSON.stringify(text);
Indexed collections in JavaScript refer to data structures like arrays, where elements are
stored and accessed by numerical indices. Arrays allow for efficient storage and retrieval of
ordered data, providing methods for manipulation and traversal of their elements.
Example
an array called ‘student’ contains the names of the students and the index values are the
Roll Numbers of the students. JavaScript does not have an explicit array data type. However,
we can use the predefined Array object in JavaScript and its methods to work with arrays.
Creating an Array: There are many ways to create and initialize an array that is listed
below:
Creating arrays without defining the array length. In this case, the length is equal to the
number of arguments.
Syntax:
Syntax:
arr.length = 6;
Array Methods
Use indices to access array elements. Indices of Arrays are zero-based which means the index
of the elements begins with zero.
javascript
console.log(fruits [0]);
console.log(fruits[1]);
Output
Apple
Mango
javascript
console.log(fruits.length)
Output
javascript
console.log(fruits[i]);
Output
Apple
Mango
Banana
JavaScript forEach() Loop: The forEach() function provides once for each element of the
array. The provided function may perform any kind of operation on the elements of the given
array.
javascript
fruits.forEach(function (fruit) {
console.log(fruit);
});
Output
Apple
Mango
Banana
javascript
const fruits = ['Apple', 'Mango', 'Banana'];
Output
Apple
Mango
Banana
Array Methods
There are various array methods available to us for working on arrays. These are:
JavaScript push() Method: This method adds one or more elements to the end of an array
and returns the resulting length of the array.
javascript
numbers.push('3');
console.log(numbers);
Output
JavaScript pop() Method: This method removes the last element from an array and returns
that element.
javascript
console.log(last);
Output
JavaScript concat() Method: This method joins two arrays and returns a new array.
javascript
console.log(myArray);
Output
JavaScript join() Method: This method creates a string by joining all the elements of an
array.
javascript
console.log(list);
Output
javascript
myArray.sort();
console.log(myArray);
Output
JavaScript indexOf() Method: This method searches the array for an Element and returns
the index of the first occurrence of the element.
javascript
Output
JavaScript shift() Method: This method removes the first element from an array and returns
that element.
javascript
console.log(first);
Output
JavaScript reverse() Method: This method reverses the first array element become the last
and the last becomes the first. It transposes all the elements in an array in this manner and
returns a reference to the array.
javascript
myArr.reverse();
console.log(myArr);
Output
JavaScript map() Method: This method returns a new array of the returned value from
executing a function on every array item.
javascript
return item.toUpperCase();
});
console.log(a2);
Output
JavaScript filter() Method: This method returns a new array containing the items for which
the function returned true.
javascript
});
console.log(a2);
Output
[ 10, 20, 30 ]
Typed Arrays:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Typed_arrays#views
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/
TypedArray
Equality Comparisons:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/
Equality_comparisons_and_sameness
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
https://www.javascript.com/learn/conditionals#:~:text=Conditional%20statements
%20control%20behavior%20in,for%20a%20block%20of%20code.
if else:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
switch:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
throw:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
try/catch/finally:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/
try...catch