JavaScript bootcamp · Lab 19

Second largest

mediumArrays12 minLesson: Array Methods

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 and log the second largest distinct value.

If the biggest number appears twice, the second largest is still the next different number down.

Input. One line: integers separated by spaces (at least two distinct values).

Output. One integer: the second largest distinct value.

Examples

Example 1 — Two 7s collapse to one, so second largest is 4.
Input
4 1 7 7 3
Output
4
Example 2
Input
10 20 30
Output
20
Hint
  1. new Set(nums) drops duplicates; spread it back to an array.
  2. Numeric sort needs a comparator: .sort((a, b) => a - b). The default sort is alphabetical!
Show correct code

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

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