JavaScript Set Practice: Remove Duplicate Values

Duplicate values appear in tag lists, search history and imported data. A Set is a built-in collection that keeps only one copy of each value. This exercise turns a noisy array into a clean list while keeping the original order of first appearance.

Before you start: Arrays, strings and the spread operator.

Your task

Use a Set to remove duplicate tags while keeping the order in which each tag first appears. Print the unique tags on one line, separated by a comma and a space.

Starter code

const tags = ["js", "css", "js", "html", "css", "js"];

// Print the unique tags on one line.

Expected result

js, css, html
Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Create a Set from the array, spread it into a new array, then join the values with a comma and a space.

Show the complete solution and walkthrough
const tags = ["js", "css", "js", "html", "css", "js"];

// Print the unique tags on one line.
const unique = [...new Set(tags)];
console.log(unique.join(", "));
  1. Pass the tags array to new Set(tags). The Set ignores a value that it already contains, so js, css and html each remain once.
  2. Spread the Set into an array literal. This gives you a normal array again, in the order the values were first added.
  3. Call join(", ") on that array and print the string. The result is js, css, html.

A common mistake

Using indexOf inside a loop also works, but it re-scans the array every time. Also remember that a Set compares values strictly, so "JS" and "js" are different tags.

Try an edge case

An empty array produces an empty line. Numbers and strings are different values, so 1 and "1" would both be kept.

Take it one step further

Lowercase every tag before building the Set so that "JS" and "js" count as one tag. Then print how many unique tags remain.

Read the javascript tool guide