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
>Solution :
To check if a value is "in" a Set, use .has()
The has() method returns a boolean indicating whether an element with the specified value exists in a Set object or not.
In your case this would be:
if (searchData.has(element)) {
Updated snippet
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 => {
//console.log(element, element in searchData, searchData.has(element))
if (searchData.has(element)) {
noDupes.delete(element)
}
})
return [...noDupes]
}
console.log(transformSearchFields(dupArr));
There are other methods filter data (as provided in other answer, so not repeated here).