To remove items from a set based on a condition in JavaScript, you can use the forEach
method combined with the delete
method.
In this example,
numberSet
with values const numberSet = new Set([1, 2, 3, 4, 5]);
.forEach
method.forEach
method, we check if the current number is even.delete
method of the set.const numberSet = new Set([1, 2, 3, 4, 5]);
console.log("Original Set:", numberSet);
numberSet.forEach((number) => {
if (number % 2 === 0) {
numberSet.delete(number);
}
});
console.log("Set after removing even numbers:", numberSet);
Original Set: Set { 1, 2, 3, 4, 5 } Set after removing even numbers: Set { 1, 3, 5 }
In this example,
stringSet
with values const stringSet = new Set(["apple", "banana", "orange", "kiwi"]);
.forEach
method.forEach
method, we check if the length of the current string is greater than 4.delete
method of the set.const stringSet = new Set(["apple", "banana", "orange", "kiwi"]);
console.log("Original Set:", stringSet);
stringSet.forEach((str) => {
if (str.length > 4) {
stringSet.delete(str);
}
});
console.log("Set after removing strings longer than 4 characters:", stringSet);
Original Set: Set { 'apple', 'banana', 'orange', 'kiwi' } Set after removing strings longer than 4 characters: Set { 'kiwi' }
In this tutorial, we learned How to Remove Items from Set based on a Condition in JavaScript language with well detailed examples.