Removing An Element
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 31 of 65.
To remove an element from a Set, use the delete() method. This method removes the specified element from the Set if it exists. If the element doesn't exist, the Set remains unchanged.
Here's how to use the delete() method:
const mySet = new Set([1, 2, 3, 4, 5]);
mySet.delete(3);
console.log(mySet); // Set(4) { 1, 2, 4, 5 }
// Trying to delete a non-existent element
mySet.delete(10);
console.log(mySet); // Set(4) { 1, 2, 4, 5 } (unchanged)The delete() method returns a boolean indicating whether the element was successfully removed:
console.log(mySet.delete(2)); // true
console.log(mySet.delete(10)); // falseChallenge
EasyCreate a function called removeMultiples that takes two parameters: an array of numbers and a number n. The function should convert the array to a set, and remove all multiples of n from the Set (including n itself if it's in the Set). Finally convert the set to an array and return it.
Multiples are the numbers you get when you multiply a given number (n) by all whole numbers (1, 2, 3, etc.).
For example, if n = 3:
- The multiples of 3 are: 3, 6, 9, 12, 15, 18, 21, 24, and so on...
Cheat sheet
To remove an element from a Set, use the delete() method:
const mySet = new Set([1, 2, 3, 4, 5]);
mySet.delete(3);
console.log(mySet); // Set(4) { 1, 2, 4, 5 }The delete() method returns a boolean indicating whether the element was successfully removed:
console.log(mySet.delete(2)); // true (element existed and was removed)
console.log(mySet.delete(10)); // false (element didn't exist)If the element doesn't exist in the Set, it remains unchanged and delete() returns false.
Try it yourself
function removeMultiples(arr, n) {
// 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