Site icon i2tutorials

Javascript-Set

Javascript-Set

 

A javascript set is a collection of items that are unique i.e no element can be repeated. Set in ES6(ECMAScript 6) is ordered: elements of the set can be iterated in the insertion order. Set can store any type of values whether objects or primitive values.

 

Syntax:

 

new Set([it]);

 

Returns:

 

A new set object

 

Example:

 

// it contains
// ["sumit","amit","anil","anish"]
var set1 = new Set(["sumit","sumit","amit","anil","anish"]);

// it contains 'f', 'o', 'd'
var set2 = new Set("fooooooood");

// it contains [10, 20, 30, 40]
var set3 = new Set([10, 20, 30, 30, 40, 40]);

// it is an  empty set
var set4 = new Set();

 

Main methods are:

 

 

Set is just the right thing for that:

 

<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "p8hj2rbs3i";

let set = new Set();

let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);

// set keeps only unique values
alert( set.size ); // 3

for (let user of set) {
 alert(user.name); // John (then Pete and Mary)
}
</script>

 

Exit mobile version