Return Largest Numbers in Arrays - Repeating element?

Return Largest Numbers in Arrays - Repeating element?
0

#1

The first element in the new array is getting carried over to the second element when I return result I can’t figure out why. Anyone notice anything that I’m missing to prevent this from happening?

Your code so far

function largestOfFour(arr) {
  var result = [];
  var numHolder = 0;
  for (var i = 0;i < arr.length;i++) {
    for (var j = 0;j < arr[i].length;j++) {
      if (arr[i][j] > numHolder) {
        numHolder = arr[i][j];
      }
    }result.push(numHolder);
  }return result;
}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36.

Link to the challenge:


#2

When the first array is evaluated the numHolder variable has the value that is largest in the array which in your case is 27
numHolder=27;
but then when it evaluates the second array every element is smaller than the current numHolder value so the numHolder value remains the same and 27 is again pushed to the result array.
So to stop this from happening you will have to re-initialize the numHolder variable every singe time an array is eveluated .


#3

Thank you! I knew it was somehow getting caught up on the biggest number in the first array. I just couldn’t figure out for the life of me how to reinit the numHolder variable before moving to the next array.


#4

you just need to put numHolder = 0; inside the first for loop so that everytime an array is evaluated initially numHolderis 0


#5

Simply you can complete this challenge using push and sort function.

  function largestOfFour(arr) {
  var array=[];
  for(var i=0; i<arr.length;i++){
     array.push(arr[i].sort(function (a, b){ return a-b;})[arr.length-1]);
  }
     return array;
  }
 largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);