How to find the second largest element from an array (Java script)

 


function getSecondLargest(nums) {

  //remove any duplicate from array    
  let arr_unique = [...new Set(nums)];

  //compare each element and return the largest element from array
  let arr = arr_unique.reduce((first_elesecond_ele=> {
    return Math.max(first_elesecond_ele)
  });

  //find the index of largest element
  let max_value_index = arr_unique.indexOf(arr);

  // delete the largest element from the array
  arr_unique.splice(max_value_index, 1);

  //again find the largest element from the new array 
  //this largest element is automaticlly the second largest
  let second_largest = Math.max(...arr_unique);
  return second_largest
}

const nums = [12010810922042821922451123600343746];
console.log(getSecondLargest(nums));

0 Comments