-1

How do I get to display the elements that make up the intersection of two sets without it displaying [object set] ?

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

function intersection(setA, setB) {
  const result = new Set();
  for (const elem of setA) {
    if (setB.has(elem)) { 
      result.add(elem);
    } 
  }
  return result; 
}

console.log(intersection(setA, setB));
Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56
  • 1
    check out this answer: https://stackoverflow.com/questions/47243139/how-to-convert-set-to-string-with-space – robbieAreBest Jun 27 '22 at 12:29
  • There are several different ways. MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – ryanwebjackson Jun 27 '22 at 12:47

1 Answers1

3

Use Array.from e.g.:

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

function intersection(setA, setB) {
  const result = new Set();
  for (const elem of setA) {
    if (setB.has(elem)) { 
      result.add(elem);
    } 
  }
  return result; 
}

const matches = Array.from(intersection(setA, setB));
console.log(matches);
Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56