Day 3: Arrays in JavaScript | 10 Days Of JavaScript

Hello there, today we are going to solve Day 3: Arrays Hacker Rank Solution in JavaScript which is a Part of 10 Days Of JavaScript Series.

Hello there, today we are going to solve Day 3: Arrays Hacker Rank Solution in JavaScript which is a Part of 10 Days Of JavaScript Series.

Day 3: Arrays in JavaScript
Table Of Contents 👊

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++];
}

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));
}

Disclaimer: The above Problem (Arrays) is generated by Hacker Rank but the Solution is Provided by Sloth Coders. This tutorial is only for Educational and Learning Purpose.

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

Post a Comment