Adding and deleting element within a set object in Javascript

The javascript set object has been introduced in ECMAScripts 6 and just like the array it allows us to add in element or removing element from it. In below example we are going to create a set and do the adding and removing element process. First of all, lets create an instance of the set and the sum variable which we will then use to sum up all the elements within the set later on.

let counting = new Set();
let sum = 0;

Next we will add numbers into the set plus sum up all those numbers within that set.

for(let i = 0; i < 10; i++) {

counting.forEach(function (number) {
	sum += number;

console.log(sum); // output 45

Now we will delete a random number (from 0 to 9) within that set and then get the sum again!

let number_delete = 0;

counting.delete(number_delete = Math.floor(Math.random() * 10))

sum = 0;

counting.forEach(function (number) {
	sum += number;

console.log("Delete number " + number_delete); // output Delete number 2
console.log(sum); // output 43

The different of set and array is that set only collect unique value while an array will allow duplicate value within that array.

Leave a Reply

Be the First to Comment!

Notify of