Skip to main content

Command Palette

Search for a command to run...

[JavaScript] Set Object That You Want To Use for an Object With Unique Values - Explained with Examples.

Updated
2 min read
[JavaScript] Set Object That You Want To Use for an Object With Unique Values - Explained with Examples.
L

Computer Science Enthusiast with a Drive for Excellence | Data Science | Web Development | Passionate About Tech & Innovation

Beginner Friendly. Explore what Set Object in JavaScript is, and how they are used. Check out how they differentiate from the object.


Introduction

What would you do if you want to have an array with unique values (no duplicated values)?

One way to do that is to use the characteristic of an object because the object's key cannot be duplicated.

However, JavaScript has an object called Set which allows for doing that task more efficiently.


Set Object

Without Set Object, you might need to create an object and then create a new array with unique values.

let foodArray = ["Burger", "Taco", "Burger", "Sandwich", "Pasta", "Pasta"];
let oFood = {};
for (const food of foodArray) {
    oFood[food] = ""; // creating unique key-value pairs.
}

let uniqueFood = [];
for (const food in oFood) {
    uniqueFood.push(food); // this wil create an array with no duplicated elements (or values)
}

But that involves 2-steps. We can use Set Object to make it easier.

add() and delete() method:

let foodSet = new Set();
foodSet.add("Burger");
foodSet.add("Taco");
foodSet.add("Sandwich");
foodSet.add("Pasta");

foodSet.forEach(function(food) {
    console.log(food);
});

// Burger
// Taco
// Sandwich
// Pasta

foodSet.delete("Pasta");
foodSet.forEach(function(food) {
    console.log(food);
});

// Burger
// Taco
// Sandwich

has() method:

let foodSet = new Set();
foodSet.add("Burger");
foodSet.add("Taco");
foodSet.add("Sandwich");
foodSet.add("Pasta");

console.log(foodSet.has("Burger")); // true

size property and clear() method:

let foodSet = new Set();
foodSet.add("Burger");
foodSet.add("Taco");
foodSet.add("Sandwich");
foodSet.add("Pasta");

console.log(foodSet.size); // 4
console.log(clear()); // clears out everything

More from this blog

Jay's Dev Blog

90 posts

Consistency is what transforms average to excellence.