To create a set of size N in JavaScript, you can use a loop to add elements to a Set object until it reaches the desired size.
In this example,
createSetOfSizeN
that takes an integer n
as a parameter. This parameter represents the desired size of the set.set
.for
loop to add integers from 1 to n
to the set using the add
method of the Set object.createSetOfSizeN
with a specific size (e.g., 5) and store the result in a variable named mySet
.console.log
.function createSetOfSizeN(n) {
let set = new Set();
for (let i = 1; i <= n; i++) {
set.add(i);
}
return set;
}
let mySet = createSetOfSizeN(5);
console.log(`Created set of size 5 with sequential numbers: ${JSON.stringify(Array.from(mySet))}`);
Created set of size 5 with sequential numbers: [1,2,3,4,5]
In this example,
createRandomSetOfSizeN
that takes an integer n
as a parameter. This parameter represents the desired size of the set.set
.while
loop to add random numbers to the set until it reaches the desired size. The Math.random()
function generates a random number between 0 (inclusive) and 1 (exclusive).createRandomSetOfSizeN
with a specific size (e.g., 5) and store the result in a variable named myRandomSet
.console.log
.function createRandomSetOfSizeN(n) {
let set = new Set();
while (set.size < n) {
let randomNumber = Math.floor(Math.random() * 100) + 1; // Generate random number between 1 and 100
set.add(randomNumber);
}
return set;
}
let myRandomSet = createRandomSetOfSizeN(5);
console.log(`Created set of size 5 with random numbers: ${JSON.stringify(Array.from(myRandomSet))}`);
Created set of size 5 with random numbers: [35,57,18,91,74]
In this tutorial, we learned How to create a Set of size N in JavaScript language with well detailed examples.