Reputation: 3
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]))
Upvotes: 0
Views: 759
Reputation: 1
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
Upvotes: 0
Reputation: 177885
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) => b-a)[1]; // sorts in descending numerical order
console.log(getSecondLargest([8,7,9,4,5,6,3,2.10,22,42,101]))
Upvotes: 0
Reputation: 2121
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) => a-b);
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]))
Upvotes: 2