How to get the second largest element of an array in JavaScript Hacker Rank Question
Hy Friends, Today we will learn How to get a second largest element of array in JavaScript.
This question asked mostly in Interviews.
We can do resolve this in different ways. So lets' Start.
Let's Assume we have Array
let arr = [ 100, 23 , 45, 145, 44, 22, 5, 6, 33, 55]
First Way - First we will sort an array in descending order using the javascript sort function and then get the second index. this will be our second largest element of an array.
arr.sort( (a,b) => b - a)[1] // output 100
Here I have used the arrow function.
Second Way -
Step 1- Second way we will get the max number of the array element and store in a variable.
var highest = Math.max.apply('',arr);
Step 2 - Get the index of the largest number.
var highestIndex = arr.indexOf(highest);
Step 3 - Assign zero or negative value to the array (arr)
arr[highestIndex] = 0 ; // - Infinity , -1
Step 4 - Now again get max number using Math.max.apply function
var secondHighest = Math.max.apply('',arr);
// output -> 100
Yeah! You have learned ЁЯШКI hope you understood and like this article. if you like it so, please give feedback in the comment section.If any mistakes I made here, so please let me know and improve me.If you have any query, feel free to ask me ЁЯШКRecommended post
- How to Encode and Decode Strings with Base64 in JavaScript examples
- How to create QR code Genereator using Jquery
- How to shift button in Clock wise in javaScript using ECMA6?
- How to Reset DropDownList Selection Using jQuery?
- Create dynamic drop-down list option with JavaScript and jQuery
- Onclick show and hide div using JQuery with examples
- How to Get All Google play store apps List using PHP Scraper?
- How to pass a variable from the command line using PHP?
- How to Submit Registration and Login Form in PHP?
- Introduction PHP
- how to declare variables in PHP?
- What things you need to install PHP?
- How to get meta tags in 2 easy way in PHP
Post a Comment
Please do not enter any spam link in the comment section.