4

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];
}
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 1
    make sure you are parsing the values as integers or floats and not strings because 10 is after 1 alphabetically – full-stack Aug 13 '20 at 18:25
  • please add the code to the question. what does not work? – Nina Scholz Aug 13 '20 at 18:26
  • 1
    The issue here is that if you use the `sort()` method alone, `1 < 10 < 2`. If you run `[1,2,3,4,5,6,7,8,9,10].sort()` you see that the result is `[1,10,2,3,4,5,6,7,8,9]` – johannchopin Aug 13 '20 at 18:39
  • *"The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values."* - [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – 3limin4t0r Aug 13 '20 at 18:45
  • Got the answer ,Thanks everybody for helping me out.I didn't knew how sort() works .... – ANKIT AYUSH Aug 13 '20 at 19:01

4 Answers4

5

try this

let intArray =[1,2,3,4,5,6,7,8,9,10];
console.log(intArray.sort((a, b) => b - a)[1]);
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
2

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));
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

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...

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

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];
}
Yogesh
  • 366
  • 2
  • 16