I’m doing a hacker rank challenge and I can’t figure out why my solution won’t work.

function getSecondLargest(nums) {
var big = Math.max.apply(Math, nums);
for (var i = 0; i < nums.length; i++) {
if (nums[i] == big) {
nums.splice(nums[i], 1);
console.log(nums);
}
}
for (var i = 0; i < nums.length; i++) {
var secondBig = Math.max.apply(Math, nums);
if (nums[i] == secondBig) {
return nums[i];
}
}
}

A couple of tips. The first one is that you can do the Math.max in a way that I like more since I’m a noob. The way you do this is:

Math.max(…nums);

I like that much more.

The issue that’s causing your code not to work is in your splice.

Hint: As it is right now, let’s say nums = [10, 20, 30, 40]. When big (40) == nums[i], you’re asking to splice at index nums[i] which would be index 40

Yes, I see now. I’ve tried replacing it with nums.splice(indexOf(big), 1); But that doesnt seem to work either.
or maybe?
nums.splice(nums[indexOf(big)], 1);

I’ve been stuck on this longer then I’d like to admit…

I solved it for all test cases. I feel I made this much more complex then it needed to be but hey it worked.

function getSecondLargest(nums) {
var big = Math.max.apply(Math, nums);
for (var i = 0; i < nums.length; i++) {
if (nums[i] == big) {
var removed = nums.splice(i, 1);
for (var j = 0; j < nums.length; j++) {
if (nums[j] == Number(removed)) {
getSecondLargest(nums);
}
}
}
}
for (var i = 0; i < nums.length; i++) {
var secondBig = Math.max.apply(Math, nums);
if (nums[i] == secondBig) {
return nums[i];
}
}
}

haha good job! That is complicated! Since you finished yours, I’ll show you what I came up with!

function getSecondLargest(nums) {
let biggest = Math.max(...nums);
let newArr = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== biggest) {
newArr.push(nums[i]);
}
}
return Math.max(...newArr);
}

Set is data structure like array (but not really array) where every element is unique.
If you pass array as an argument when creating a Set, it’ll remove all duplicates. Then using spread (...) you can convert Set to an array.

This is the modern way to remove duplicates from an array: