Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of map in javascript

Tags:

javascript

I want to print the size of map in javascript. I used the command map.size but the answer is coming 0 which is not correct.

Here is my source code:

<div id="demo" ></div>
<script>
    function add(test, key, value) {
        if (!test[key]) 
            test[key] = [value];
        else 
            test[key].push(value);
    }
    var mapp = new Map();
    var i,j,k=0;
    for (i=0;i<5;i++)
    {
      for (j=0;j<i;j++)
      add(mapp,i,j);
    }
    document.getElementById('demo').innerHTML="Map size are: "+ mapp.size;
</script>

Output: Map size are: 0

However, when I am printing the map entries:

for (var m in mapp)
{
        for (k=0;k<mapp[m].length;k++)
        document.write(mapp[m][k]+"  ");

      document.write("<br>");
}

I can see the output:

0 
0 1 
0 1 2 
0 1 2 3 

Please tell me how to find the size of map and why the above code mapp.size is not working.

like image 939
Ratnesh Avatar asked Feb 04 '19 15:02

Ratnesh


People also ask

How do you find the size of a Map?

HashMap. size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map. Parameters: The method does not take any parameters. Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map.

How big can a JavaScript Map be?

The limit is determined by: The FixedArray backing store of the Map has a maximum size of 1GB (independent of the overall heap size limit) On a 64-bit system that means 1GB / 8B = 2^30 / 2^3 = 2^27 ~= 134M maximum elements per FixedArray.

What is Map size?

Map size() method in Java is used to get the total number entries i.e, key-value pair. So this method is useful when you want total entries present on the map. If the map contains more than Integer. MAX_VALUE elements return Integer.

What is the use of Map () in JavaScript?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array.


1 Answers

You are treating Map like an array and using [] to access key/value items of it. You need to use the actual methods of Map. Instead of [], use .get() and .set().

Right now, you are setting the actual properties of the Map which are not the same as the actual tracked iterable k/v items stored by the data structure.

// Incorrect
const m1 = new Map();

m1["foo"] = "bar";

console.log(m1.length); // undefined
console.log(m1.size); // 0

// Correct
const m2 = new Map();

m2.set("foo", "bar");

console.log(m2.length); // undefined
console.log(m2.size); // 1
like image 62
zero298 Avatar answered Oct 01 '22 00:10

zero298