Javascript sets
Set
objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set
may only occur once; it is unique in the Set
's collection.
Initialize
unlike arrays sets dontt have a shortcut like square bracket for initialization we have to manually create a new instance of set class
// Arrays
const array = [];
const array = new Array()
//Sets
const set = new Set()
Add items to set
Sets are widely used for thier feature of eleminating the duplicate values
sets only contains unique items.
The values in a set can be either simple primitives like strings or integers as well as more complex object types like object literals or arrays.
const set = new Set();
set.add('Smartcodehub')
set.add(1)
set.add([1,'Neeraj'])
set.add({name:'someName'})
// if we try to add duplicate values it wont give error but the new items will not be added also
set.add('Smartcodehub')
console.log(set.length) // 4
we can add an element at the time of initialization also
const set = new Set(['Ram', 'Raj', 'Ram', 'Ram'])
set.forEach(el=>console.log(el))
// Ram
// Raj
Use Set to ensure the uniqueness of a list of values
const array = Array
.from(document.querySelectorAll('[id]'))
.map(function(e) {
return e.id
});
const set = new Set(array);
console.assert(set.size == array.length);
Iteration on set
On top of using forEach on a set, for…of loops can also be used to iterate over sets:
const animals = new Set(['hourse','tiger','elephant','cow])
for (let animal of animals) {
console.log(`${ animal }`);
}
Keys and Values
Sets also have the keys and values methods, with keys being an alias for values, so both methods do exactly the same thing. Using either of these methods returns a new iterator object with the values of the set in the same order in which they were added to the set. Here’s an example:
let partyItems = new Set(['🍕', '🍾', '🎊']);
let items = partyItems.values();
console.log(items.next());
console.log(items.next());
console.log(items.next());
console.log(items.next().done);
// Object {
// done: false,
// value: "🍕"
// }
// Object {
// done: false,
// value: "🍾"
// }
// Object {
// done: false,
// value: "🎊"
// }
// true
Remove duplicate elements from the array
this is a very common question asked in interviews. we can use Sets to solve this
const duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
const unique = [...new Set([...duplicates])]
console.log(unique)
Originally published at https://blog.smartcodehub.com on February 15, 2021.