JavaScript Sets
المعرفة:: 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¶
Has¶
Check if an element is in a set. Similar to include
method in arrays.
Add¶
ordersSet.add("Garlic Bread");
ordersSet.add("Garlic Bread");
console.log(ordersSet); // {"Pasta", "Pizza", "Risotto", "Garlic Bread"}
Delete¶
Clear¶
Iteration¶
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
Last update :
August 14, 2023
Created : August 23, 2022
Created : August 23, 2022