Saturday 20 October 2018

JavaScript: Working with Set

Set data structure is used to store unique elements.

Syntax
new Set([iterable]);

Example
var countries =  new Set();

Example 1
HelloWorld.js
var countries =  new Set();

countries.add("India");
countries.add("Australia");
countries.add("Canada");
countries.add("Germany");

for(var key of countries){
  console.log(key);
}

Output
India
Australia
Canada
Germany

Example 2
HelloWorld.js
var arr = ["India", "Australia"];

var countries =  new Set(arr);

countries.add("Canada");
countries.add("Germany");

for(var key of countries){
  console.log(key);
}


Output
India
Australia
Canada
Germany

Previous                                                 Next                                                 Home

No comments:

Post a Comment