Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over set and remove element if it is in another set and return array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To check if a value is "in" a Set, use .has()

.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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading