Adding An Element
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 30 of 65.
To add an element to a Set, use the add() method. This method adds the element to the Set if it's not already present. If the element already exists, the Set remains unchanged.
Here's how to use the add() method:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet); // Set(3) { 1, 2, 3 }You can chain multiple add() calls. This works because add() returns the Set itself, allowing you to call add() again immediately on the result:
mySet.add(4).add(5).add(6);
console.log(mySet); // Set(6) { 1, 2, 3, 4, 5, 6 }If you try to add a duplicate value, the Set will ignore it:
mySet.add(1);
console.log(mySet); // Set(6) { 1, 2, 3, 4, 5, 6 } (unchanged)Challenge
EasyCreate a function called addUniqueElements that takes two parameters: an array and another array. The function should convert the first array to a Set, and add all elements from the second array to the Set, but only if they don't already exist in the Set. Finally convert the set to an array and return it.
Cheat sheet
To add an element to a Set, use the add() method:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
console.log(mySet); // Set(2) { 1, 2 }You can chain multiple add() calls:
mySet.add(3).add(4).add(5);
console.log(mySet); // Set(5) { 1, 2, 3, 4, 5 }Sets automatically ignore duplicate values:
mySet.add(1); // Already exists, Set remains unchanged
console.log(mySet); // Set(5) { 1, 2, 3, 4, 5 }Try it yourself
function addUniqueElements(array1, array2) {
// Write your code here
}
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