JavaScript bootcamp · Lab 20

Unique and sorted

mediumSets10 minLesson: Sets

Read the question, write JavaScript on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a line of integers, remove duplicates, and log the remaining values sorted ascending on one line.

A Set dedupes; a numeric sort makes the output stable.

Input. One line: integers separated by spaces.

Output. The distinct values, ascending, space-separated.

Examples

Example 1 — Duplicates removed, order ascending.
Input
3 1 2 3 1 5
Output
1 2 3 5
Example 2
Input
4 4 4
Output
4
Hint
  1. [...new Set(nums)] gives the distinct values.
  2. Remember the numeric comparator: .sort((a, b) => a - b), then join(" ").
Show correct code

Peek only after you have tried. You can still Check your own version.

const nums = readLine().trim().split(/\s+/).map(Number);
console.log([...new Set(nums)].sort((a, b) => a - b).join(" "));
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.