We can use JavaScript to get the set size by simply using the size property of the set. The size property will simply return the number of items in the set.
var someSet = new Set(["this","is","a","set","of","size","7"]);
var length_Of_Set = someSet.size;
console.log(length_Of_Set);
#Output
7
In JavaScript, it can be useful to be able to easily calculate the size of a set.
To get the size of a set in JavaScript, we can use the size property.
Let’s use our code above and create a simple function that takes a set, and returns the size of the set.
function getSetSize(someSet){
return someSet.size;
};
And now let’s just see some examples of using this function to get the size of some sets.
Remember that sets differ from arrays in that they can only contain unique values.
function getSetSize(someSet){
return someSet.size;
};
var someSet1 = new Set(["this","is","a","set"]);
var someSet2 = new Set(["4","5","4","5"]);
var someSet3 = new Set(["red","green","blue","red","yellow","red","orange","red"]);
var someSet4 = new Set(["false","","null","undefined",null,0,"4"]);
console.log(getSetSize(someSet1));
console.log(getSetSize(someSet2));
console.log(getSetSize(someSet3));
console.log(getSetSize(someSet4));
#Output
4
2
5
7
Hopefully this article has been useful for you to learn how to use JavaScript to get set size.
Leave a Reply