10 Days Of JavaScript

Day 3: Arrays Solution

Hello Friends in this article i am gone to share Hackerrank 10 days of javascript solutions with you. | Day 3: Arrays Solution.


Also visit this link:ย  Day 2: Loops Solution


 

Day 3: Arrays Solution

Objective

In this challenge, we learn aboutย Arrays.

Function Description

Complete theย getSecondLargestย function in the editor below.
getSecondLargestย has the following parameters:

  • int nums[n]:ย an array of integers

Returns

  • int:ย the second largest number inย nums

Input Format

The first line contains an integer,ย n, the size of theย numsย array.
The second line containsย nย space-separated numbers that describe the elements inย nums.

Constraints

  • 1 <=ย nย <= 10
  • 0 <=ย numsiย <= 100, whereย numsiย is the number at indexย i.
  • The numbers inย numsย may not be distinct.

Sample Input 0

5
2 3 6 6 5

Sample Output 0

5

Explanation 0

Given the arrayย numsย = [2, 3, 6, 6, 5], we see that the largest value in the array isย 6ย and the second largest value isย 5. Thus, we returnย 5ย as our answer.

 

Solution โ€“ Day 3: Arrays


'useย strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

letย inputStringย =ย '';
letย currentLineย =ย 0;

process.stdin.on('data',ย inputStdinย =>ย {
ย ย ย ย inputStringย +=ย inputStdin;
});

process.stdin.on('end',ย _ย =>ย {
ย ย ย ย inputStringย =ย inputString.trim().split('\n').map(stringย =>ย {
ย ย ย ย ย ย ย ย returnย string.trim();
ย ย ย ย });
ย ย ย ย 
ย ย ย ย main();ย ย ย ย 
});

functionย readLine()ย {
ย ย ย ย returnย inputString[currentLine++];
}

/**
*ย ย ย Returnย theย secondย largestย numberย inย theย array.
*ย ย ย @paramย {Number[]}ย numsย -ย Anย arrayย ofย numbers.
*ย ย ย @returnย {Number}ย Theย secondย largestย numberย inย theย array.
**/
functionย getSecondLargest(nums)ย {
ย ย ย ย //ย Completeย theย function
ย ย ย ย varย sArrayย =ย nums.sort(functionย (a,b){
ย ย ย ย ย ย ย ย returnย aย -ย b;
ย ย ย ย });
ย ย ย ย varย uSarrayย =ย sArray.filter(functionย (elm,ย index,ย self){
ย ย ย ย ย ย ย ย returnย indexย ==ย self.indexOf(elm);
ย ย ย ย });
ย ย ย ย returnย uSarray[uSarray.lengthย -ย 2];
}


functionย main()ย {
ย ย ย ย constย nย =ย +(readLine());
ย ย ย ย constย numsย =ย readLine().split('ย ').map(Number);
ย ย ย ย 
ย ย ย ย console.log(getSecondLargest(nums));
}

 

 

Given the array nums = [2, 3, 6, 6, 5], we see that the largest value in the array is 6 and the second largest value is 5. Thus, we return 5 as our answer. Given the arrayย numsย = [2, 3, 6, 6, 5], we see that the largest value in the array isย 6ย and the second largest value isย 5. Thus, we returnย 5ย as our answer.