My Development Notes


Sets in JavaScript – Basics and Used Cases


Sets are a collection of unique values which never stores any duplicates. They are used to iterate through and detect multiple occurrence of the same element inside any variable, array, strings or object. The new Set() method creates a new set.

let listItems = new Set([
  "Shoes",
  "Hair-Oil",
  "Shoes",
  "Cream",
  "Lunch Box",
  "Cream",
]);

console.log(listItems);
// returns {'Shoes', 'Hair-Oil', 'Cream', 'Lunch Box'}
// an array iterated and duplicates eliminated

To return the number of elements inside a set use size property :

console.log(listItems.size);
// returns 4

To return an empty set :

console.log(new Set ());
// returns {size: 0}

To find something inside a set use has() method (similar to includes in array) :

console.log(listItems.has('Shoes'));
// returns 'true'

console.log(listItems.has('Boxes'));
// returns 'false'

To add an element to the set use add() method :

console.log(listItems.add('Onions'));
// returns {'Shoes', 'Hair-Oil', 'Cream', 'Lunch Box', 'Onions'}
// adds 'Onions' to the set

To remove an element from the set use delete() method :

console.log(listItems.delete('Hair-Oil'));
// returns 'true'

console.log(listItems);
// returns {'Shoes', 'Cream', 'Lunch Box', 'Onions'}
// 'Hair-Oil' deleted now

To delete all of the elements in a set use clear() method :

console.log(listItems.clear());
console.log(listItems);
// returns {size: 0}
// all items removed

Strings can also be iterated through in JavaScript sets :

console.log(new Set('Mak kel'));
// returns {'M', 'a', 'k', ' ', 'e', 'l'}
// the 'space' is also included

console.log(new Set('Mak Kel'));
//returns {'M', 'a', 'k', ' ', 'K', 'e', 'l'}
// notice how 'k' and 'K' are treated differently

Some examples of Used Cases in JavaScript Sets

const depttEmployee = [
  "Sales Agent",
  "Guard",
  "Operator",
  "Guard",
  "Manager",
  "Sales Agent",
  "IT Specialist",
  "Executive",
];

const EmpTypes = new Set(depttEmployee);
console.log(EmpTypes);

// returns {'Sales Agent', 'Guard', 'Operator', 'Manager', 'IT Specialist', 'Executive'}
console.log(new Set('markshiekkeldht')).size;
// returns 11 unique elements from the string

Note: Sets are not intended to replace arrays, arrays are meant to be used whenever needed. Only when you want to filter out unique values, you can use sets.


Leave a Reply

Your email address will not be published. Required fields are marked *