JavaScript Second Largest Element in array Error in code

Viewed 98

I wrote this code to get second max...it worked in cases like nums=[1,2,3,2,4] and i got second max equal to 3.But if mu array is [1,2,3,4,5,6,7,8,9,10] the output for second max is 8. Please help.

function getSecondLargest(arr){
  let uniqueArr = [ ...new Set(arr) ];
  uniqueArr.sort();
  const z= uniqueArr.length;
  return arr[z-2];
}
4 Answers

try this

let intArray =[1,2,3,4,5,6,7,8,9,10];
console.log(intArray.sort((a, b) => b - a)[1]);

Try this:

let arr = [1,2,3,4,5,6,7,8,9,10];

function getSecondLargest(nums){
    let sort = arr.sort((a, b) => a - b);
    return sort[sort.length - 2]
}

console.log(getSecondLargest(arr));

It is sorting the elements alphabetically. Try passing the function in the sort:

let arr1 = [1,2,3,2,4];
let arr2 = [1,2,3,4,5,6,7,8,9,10];

console.log( getSecondLargest(arr1) );
console.log( getSecondLargest(arr2) );

function getSecondLargest(arr){
  let uniqueArr = [ ...new Set(arr) ];
  uniqueArr.sort((a,b)=> a-b);
  const z= uniqueArr.length;
  return arr[z-2];
}

I recommend you take care of edge cases such as arrays of length 0 or 1...

It is returning 8 because sort() method in javascript by default sorts the array in alphabetical order, so applying sort() method to your will return something like this:-

[1,10,2,3,4,5,6,7,8,9]

So, in order to sort them numerically, you've to add this new method which is further simplified by using arrows functions in ES6. Following will be your updated code:-

function getSecondLargest(arr){
  let uniqueArr = [ ...new Set(arr) ];
  uniqueArray.sort((a,b) => a-b);
  const z= uniqueArr.length;
  return arr[z-2];
}

Related