In this post I’m going to show you one possible solution of one of the 10 Days of JavaScript challenges from Hackerrank. We’re going to use Set object to return a second largest number from an original array.
Challenge
Full description of the challenge: 10 Days of JavaScript. Day 3: arrays. I really recommend registering and trying these challenges by yourself.
Solution and explanation
It would be rather simple task if the input array would always have distinct numbers, but it’s not the case. We might get an array like this: [2, 3, 6, 6, 5]. In that case the function should return 5.
We could try to sort numbers in an array in the descending order and then compare them from the top to find the second largest number and not simply second number in the array. But there is a smarter way to do it. We simply need to create a Set object. Set objects have only distinct values so if we create Set object from an array, we’re left with distinct values only (new Set(nums)). Then, we basically build am array from Set object’s elements (nums = […new Set(nums)];).
Once we have that array, we can retrieve the largest number (Math.max(…nums)). Then we get it’s index, because we need it to be able to remove the value from the array. We use splice method for that. It needs two arguments: the first is the start index where we start the operation and the second is number of elements to remove. After this our array’s largest number is the second largest number of the original array.