find two largest numbers in array javascript code example

Example 1: how to find the smallest two numbers in an array javascript

function sumTwoSmallestNumbers(numbers) {  
  numbers = numbers.sort((a, b) => {
    return a - b; });
};  //this will turn the numbers list into the 2 lowest numbers

Example 2: 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
};

Example 3: find second largest number in array javascript

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