LearnFrenzy
Sign in Take a free test

ES6 Features · ES6 Features Coding Problems · Question 7

Union, intersection and difference with Sets in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Two batches list the skills of candidates. Print all skills, the skills common to both, and the skills only in the first batch.

Solution
main.js
const batchA = new Set(["js", "react", "sql", "git"]);
const batchB = new Set(["python", "sql", "git", "docker"]);

const union = new Set([...batchA, ...batchB]);
const intersection = [...batchA].filter((s) => batchB.has(s));
const onlyA = [...batchA].filter((s) => !batchB.has(s));

console.log("All:", [...union].join(", "));
console.log("Common:", intersection.join(", "));
console.log("Only A:", onlyA.join(", "));

Output Verified by running it on Node.js

All: js, react, sql, git, python, docker
Common: sql, git
Only A: js, react

Spreading both Sets into a new Set merges them without duplicates; filter with has gives the intersection and the difference. (Newer engines also have union/intersection methods on Set.prototype.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links