How to find the size of map in 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 ></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.

4

5 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
3

Map type has a special prototype to get length of the Map object

const map1 = new Map();
map1.set('a', 'alpha');
map1.set('b', 'beta');
map1.set('g', 'gamma');
console.log(map1.size);
// expected output: 3

Referance from developer.mozilla.org

Refer How to check if a Map or Set is empty?.

It works with empty map as well as map with values.

var list = {}; console.log(Object.keys(list).length );

result = 0

list = {"key":"hello"}; console.log(Object.keys(list).length );

2

You are treating Map like an Array. You should use get and set methods on map to use the inbuilt functions and not in the array fashion [ ]. Javascript cannot calculate the size of the map if you are not using it correctly

If you can't change the code, then you can have your own function to calculate the size

function getMapSize(x) { var len = 0; for (var count in x) { len++; } return len;
}
alert(getMapSize(mapp));

Comment to poster's code, the right call should look like samples in this tutorial:

Depends on data structure, for array like object, we can get map size by:

Object.getOwnPropertyNames(responseJson.result.priceMap).length;
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).length);
// logs 3
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like