-3

I will be happy if someone could help me with my problem :

I'm trying to delete the current max number form the nums Array and I couldn't get it done.

function getNthLargestNum(nums, nth) {
  debugger;
  var maxNums = [];
  for (var i = 0; i < nth; i++) {
    var nthMax = 0;
    var maxTemp = 0;

    for (var j = 0; j < nums.length; j++) {
      if (maxTemp < nums[j]) {
        maxTemp = nums[j];
        //splice();
      }
    }
    nums.splice(maxTemp, maxTemp[j]);
    maxNums.push(maxTemp);
  }
  nthMax = maxTemp;
  return nthMax;
}
var nums = [4, 5, 6, 8, 40, 60, 54, 32, 8, 1];
//var nums = [4 , 5 , 6 , 8 , 40 , 3 , 8 , 1];
var res = getNthLargestNum(nums, 3);
``
console.log(res);
ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
B.Arthur
  • 1
  • 3

2 Answers2

0

The arguments to splice() are the array index to start removing from, and the number of elements to remove. maxTemp is an array value, not an index, anx maxTemp[j] is completely meaningless since maxTemp isn't an array.

You need to use another variable to hold the index where the maximum element was found. Every time you update maxTemp, you also update maxIndex with the current index. Then you use this in the splice.

There doesn't seem to be any need for the maxNums array; you push onto it, but never use it for anything. And nthMax just holds the last value of maxTemp before you return it -- you can simply return maxTemp itself.

function getNthLargestNum(nums, nth) {
  debugger;
  var nthMax;
  for (var i = 0; i < nth; i++) {

    var maxTemp = nums[0];
    var maxIndex = 0;
    for (var j = 1; j < nums.length; j++) {
      if (maxTemp < nums[j]) {
        maxTemp = nums[j];
        maxIndex = j;
      }
    }
    nums.splice(maxIndex, 1);
  }
  return maxTemp;
}
var nums = [4, 5, 6, 8, 40, 60, 54, 32, 8, 1];
//var nums = [4 , 5 , 6 , 8 , 40 , 3 , 8 , 1];
var res = getNthLargestNum(nums, 3);

console.log(res);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If you just want to return the first of nth largest numbers you can simply do this:

function getNthLargestNum(nums, nth) {
  return nums.slice(0).sort((a, b) => b - a)[nth - 1];
}

var nums = [4, 5, 6, 8, 40, 60, 54, 32, 8, 1];
getNthLargestNum(nums, 3); // 40

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95