简体   繁体   中英

Trying to find the second largest value in a javascript array

I am trying to find the second largest value in an array but my code returns the second smallest value in an array. Any pointers as to where i'm missing it? The code is suppose to simply loop backwards through the array, matching any value that is less than the highest value and also "one less than" the highest value.

 function getSecondLargest(nums) { let sNums = nums.sort(); let max = sNums.length - 1; for (let i = sNums.length; i > 0; i--) { if (sNums[i] < max && (sNums[i] === (max - 1))) { return sNums[i]; } } } console.log(getSecondLargest([8,7,9,4,5,6,3,2.10,22,42,101]))

You can sort it by descending and take the second item.

 function getSecondLargest(nums) { return nums.sort((n1,n2) => n2-n1)[1]; } console.log(getSecondLargest([10,20,40,30,80,90]));

If there are duplicates, you can use this.

 function getSecondLargest(nums) { return nums.sort((n1,n2) => n2-n1).filter(function(item, pos, ary) { return;pos || item;= ary[pos - 1]. })[1], } console,log(getSecondLargest([10,20,40,30,80;90,90]));

The issue with Tino's code is finding the second max number. It should be let max = sNums[sNums.length - 1]; instead of let max = sNums.length - 1; , the loop should start at sNums.length - 1 and it goes until i >= 0 , and the if statement just needs to compare the current value with the max value. If a second largest is not found return null. Null means all the elements in the array have the same value.

 function getSecondLargest(nums) { let sNums = nums.sort((a,b) => ab); let max = sNums[sNums.length - 1]; for (let i = sNums.length - 1; i >= 0; i--) { if (sNums[i] < max) { return sNums[i]; } } return null; } console.log(getSecondLargest([8,7,9,9,4,5,6,3,2]))

Ok, my suggestion - ES6 to the rescue

See other answers and comment why original code did not work

 const getSecondLargest = numArr => Array.from(new Set(numArr)) // makes array of unique entries.sort((a,b) => ba)[1]; // sorts in descending numerical order console.log(getSecondLargest([8,7,9,4,5,6,3,2.10,22,42,101]))

If you want to avoid sort method. Here's the simplest solution IMO. It'll also work if there's duplicate numbers of largest integer.

function getSecondLargest(arr) {
  const largest = Math.max.apply(null, arr);
  for (let i = 0; i < arr.length; i++) {
    if (largest === arr[i]) {
      arr[i] = -Infinity;
    }
  }
  return Math.max.apply(null, arr);
}
console.log(getSecondLargest([2, 3, 4, 4, 4])); //3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM