find second largest number in array javascript
var secondMax = function (){
var arr = [20, 120, 111, 215, 54, 78]; // use int arrays
var max = Math.max.apply(null, arr); // get the max of the array
arr.splice(arr.indexOf(max), 1); // remove max from the array
return Math.max.apply(null, arr); // get the 2nd max
};
4.2
10
['20','120','111','215','54','78'].sort(function(a, b) { return b - a; })[1];
// '120'
Thank you!
10
0
5
2
var secondMax = function (arr){
var max = Math.max.apply(null, arr), // get the max of the array
maxi = arr.indexOf(max);
arr[maxi] = -Infinity; // replace max in the array with -infinity
var secondMax = Math.max.apply(null, arr); // get the new max
arr[maxi] = max;
return secondMax;
};
Thank you!
2
0
3.8
5
const arr = ['20','120','111','215','54','78', '120'];
let intArray = arr.map(Number); // convert into number
intArray = [...new Set(intArray)]; // Remove duplicate numbers
const secondLargestNumber = intArray.sort((a,b) => {
return b - a;
})[1];
console.log(secondLargestNumber) // 120
Thank you!
5
0
3.8
10
var secondMax = function (){
var arr = [20, 120, 111, 215, 54, 78]; // use int arrays
var max = Math.max.apply(null, arr); // get the max of the array
arr.splice(arr.indexOf(max), 1); // remove max from the array
return Math.max.apply(null, arr); // get the 2nd max
};
Thank you!
10
0
Are there any code examples left?
New code examples in category Javascript