Monday, April 16, 2018

JavaScript Set

A Set is a collection of values, where each value may occur only once.

Its main methods are:

new Set(iterable)  –  creates the set, optionally from an array of values.
set.add(value)       –  adds a value, returns the set itself.
set.delete(value)  –  removes the value, returns true if value existed at the moment of the call, else false.
set.has(value)       –   returns true if the value exists in the set, else false.
set.clear()             –   clear everything from the set.
set.size                 –   the elements count.

Example I:


let set = new Set();

let test1 = { name: "test1" };
let test2 = { name: "test2" };
let test3 = { name: "test3" };

set.add(test1);
set.add(test2);
set.add(test3);
set.add(test1);
set.add(test3);

// Unique only allowed
alert( set.size ); // 3

for (let user of set) {
  alert(user.name); // test1 (then test2 and test3)
}

For uniqueness, you can go ahead with set.

Set Iteration :

Below are supported methods with set iterator.

set.keys() – returns an iterable object for values.
set.values() – same as set.keys, for compatibility with Map.
set.entries() – returns an iterable object for entries [value, value], exists for compatibility with Map.

Note: Map also have the same above.



let setExample = new Set(["oranges", "apples", "Mango"]);

for (let value of setExample) alert(value);

// the same with ES6 for each
setExample.forEach((value, valueAgain, set) => {
  alert(value);
});






No comments:

Post a Comment