المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: The Complete JavaScript Course 2022 From Zero to Expert


  • Sets are collections of unique values. Items order is irrelevant and there’s no access by index.
// Sets
const ordersSet = new Set(["Pasta", "Pizza", "Pizza", "Risotto", "Pasta", "Pizza"]);
console.log(ordersSet); // {"Pasta", "Pizza", "Risotto"}
 
console.log(new Set("Jonas")); // {"J", "o", "n", "a", "s"}

Methods

Size

console.log(ordersSet.size); // 3

Has

Check if an element is in a set. Similar to include method in arrays.

console.log(ordersSet.has("Pizza")); // true
console.log(ordersSet.has("Bread")); // false

Add

ordersSet.add("Garlic Bread");
ordersSet.add("Garlic Bread");
console.log(ordersSet); // {"Pasta", "Pizza", "Risotto", "Garlic Bread"}

Delete

ordersSet.delete("Risotto");
console.log(ordersSet); // {"Pasta", "Pizza", "Garlic Bread"}

Clear

// ordersSet.clear();
console.log(ordersSet); // {}

Iteration

for (const order of ordersSet) console.log(order);

Examples

Remove duplicates form an array

const staff = ["Waiter", "Chef", "Waiter", "Manager", "Chef", "Waiter"];
// const staffUnique = new Set(staff);
console.log(staffUnique); // {'Waiter', 'Chef', 'Manager'}
const staffUnique = [...new Set(staff)];
console.log(staffUnique); // ['Waiter', 'Chef', 'Manager']

Get size of unique element of an array or string

console.log(new Set(["Waiter", "Chef", "Waiter", "Manager", "Chef", "Waiter"]).size); // 3
console.log(new Set("jonasschmedtmann").size); // 1