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_ele, second_ele) => {
    return Math.max(first_ele, second_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 = [120, 108, 109, 220, 428, 2, 19, 22, 45, 1, 1, 23, 600, 34, 37, 46];
console.log(getSecondLargest(nums));

0 Comments