To filter items of a set based on a condition in JavaScript, you can use the filter()
method to create a new set containing only the elements that pass the condition.
In this example,
numberSet
with values {1, 2, 3, 4, 5, 6}
.filter()
method on numberSet
to create a new Set containing only the even numbers. We provide a function as the argument to filter()
that checks if each number is even using the modulo operator %
.const numberSet = new Set([1, 2, 3, 4, 5, 6]);
const evenNumbers = new Set([...numberSet].filter(num => num % 2 === 0));
console.log('Even numbers:', evenNumbers);
Even numbers: Set { 2, 4, 6 }
In this example,
stringSet
with values {'Apple', 'Banana', 'Apricot', 'Orange'}
.filter()
method on stringSet
to create a new Set containing only the strings starting with 'A'. We provide a function as the argument to filter()
that checks if each string starts with 'A' using the startsWith()
method.const stringSet = new Set(['Apple', 'Banana', 'Apricot', 'Orange']);
const filteredStrings = new Set([...stringSet].filter(str => str.startsWith('A')));
console.log('Strings starting with A:', filteredStrings);
Strings starting with A: Set { 'Apple', 'Apricot' }
In this tutorial, we learned How to Filter Items of a Set based on a Condition in JavaScript language with well detailed examples.