Copy And Clear
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 34 of 65.
Sets provide two methods for creating copies and clearing all elements:
new Set(existingSet): Creates a new Set with all elements from the existing Set.clear(): Removes all elements from the Set.
Here's how to create a copy of a Set:
const originalSet = new Set([1, 2, 3, 4, 5]);
const copiedSet = new Set(originalSet);
console.log(copiedSet); // Set(5) { 1, 2, 3, 4, 5 }To clear all elements from a Set:
const mySet = new Set([1, 2, 3, 4, 5]);
console.log(mySet.size); // 5
mySet.clear();
console.log(mySet.size); // 0Challenge
EasyCreate a function called setOperations that takes an array as a parameter. The function should convert the array to a set and:
- Create a copy of the input Set
- Add the number 10 to the copied Set
- Clear the original Set
- Return an object with two properties:
copiedSet(the modified copy) andoriginalSet(the cleared original Set)
Cheat sheet
To create a copy of a Set, use the Set constructor with the existing Set:
const originalSet = new Set([1, 2, 3, 4, 5]);
const copiedSet = new Set(originalSet);To remove all elements from a Set, use the clear() method:
const mySet = new Set([1, 2, 3, 4, 5]);
mySet.clear(); // Set is now emptyTry it yourself
function setOperations(inputArr) {
const inputSet = new Set(inputArr);
// Write your code here
return {
copiedSet: copiedSet,
originalSet: inputSet
};
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys