I am not sure what I am missing from my function here to remove elements in a a set. It seems the loop is not working as expected. If you have a more optimal solution O(1), please share. Thanks!
const dupArr = ["a", "b", "c", "d", "d",'dog']
function transformSearchFields(fields) {
let noDupes = new Set(fields)
const searchData = new Set(['dog', 'a'])
// iterate over noDupes set and check if element is in the searchData set. If it is, remove the element from the noDupes set
noDupes.forEach(element => {
if (element in searchData) {
noDupes.delete(element)
}
})
return [...noDupes]
}
// desired output: ["b", "c", "d"]
I expected the loop to remove values that were in the searchData set
4
Answers
Here is example how you can filter an array with unique values in response:
To check if a value is "in" a Set, use .has()
In your case this would be:
Updated snippet
There are other methods filter data (as provided in other answer, so not repeated here).
You could take the
Set
directly and omit items of this the for filtering.You can convert your dupArr Set to array again with spread operator and use
filter
with thehas
method for your searchData Set