
Here we will learn the Basic javascript concept of map which is very useful in day-to-day code as it is very time-efficient
We mainly use two options for storing multiple sets of data into a single variable 1. Array 2.Map.So the basic problem with the array is that if we need to search through the array of any specific element, we must loop through the whole array. But on the other hand in the map, it is straightforward and we can find the element in O(1) time complexity.This concept is very important when we want to code time efficient solution for any code
// Map()
const myMapfunc = new Map();
const keyString = "rk",
keyObj = {},
keyFunc = function () {};
// setting the values
myMapfunc.set(keyString, "value associated with 'a string'");
myMapfunc.set(keyObj, "value associated with keyObj");
myMapfunc.size; // 3
// getting the values
myMapfunc.get(keyString); // "value associated with 'a string'"
myMapfunc.get(keyObj); // "value associated with keyObj"
myMapfunc.get("a string"); // "value associated with 'a string'"
// because keyString === 'a string'
myMapfunc.get({}); // undefined, because keyObj !== {}
In this above code snippet, we have declared one single map and stored multiple key values in it . By providing any specific key,we can find any value that we want in O(1) time complexity. This is very beneficial in specific codes
So now next , we will learn about how we can use this technique in solving problem in efficient time.
Count element frequency of an array
This is a very popular basic question in dsa of counting multiple occurrences of all the element in the array.So if we use normal array iterating function, then we have to iterate through the whole array twice.But by using a map,we can do it by just O (1) time complexity.Let's deep dive into how we can make it in action.
function calculateElementCounts(inputArray) {
const counts = new Map();
for (const item of inputArray) {
counts.set(item, (counts.get(item) || 0) + 1);
}
return counts;
}
const inputData =
[5, 6, 6, 7, 7, 7, 8, 8, 8, 8];
const countsMap =
calculateElementCounts(inputData);
In this above code snippet, we have used a map to store all the occurrences of an element by using the get function to get the counts of all the elements in the array and updating it by one if found existing element. This algorithm is very time efficient as it gets the job done in O(1) algorithm.
By using this approach we got rid of looping the array twice which required big O (n^2) time complexity. Hence,In this blog, we learnt about how basic map works and how we can reduce and optimiise our solution by using maps.
