Menu
Coddy logo textTech

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)); // false
challenge icon

Challenge

Easy

Create 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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow