Return Largest Number in Arrays

Tell us what’s happening:

Can return ‘ar’ and ‘len’ right but returns nothing for ‘arg’. The syntax seems right and it’s no runtime error. I don’t understand why ‘len’ isn’t ‘pushed’ to ‘arg’.

Your code so far


function largestOfFour(ar) {
  	var arg = []; //to put the numbers in
  	var len = ar.length; //how many miniarrays there are
  	for(var x = 0; i<len; i++){ //loops the number of miniarrays
  		var lar = 0; //to store the biggest int of four
  		lar = ar[0]; //lar = firstnum of miniarray
		for(var i = 0; i<4; i++){ //four times (i = 0,1,2,3)
  			if(ar[i]>lar){lar=ar[i];} //sets lar equal if(i[1/2/3] are bigger than ar[0])
  		}
  		arg.push(lar);//pushes biggest num on arg
  	}
  	return arg; //returns arg
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays

1 Like

With what could I compare it instead? And thx for your answer

Try using the Math.max and Math.min functions., here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

It worked, thanks :smile:

function largestOfFour(ar) {
  	var arg = []; //to put the numbers in
  	var len = ar.length; //how many miniarrays there are
  	for(var i = 0; i<len; i++){ //loops the number of miniarrays
  		var lar = 0; //to store the biggest int of four
  		lar = ar[0]; //lar = firstnum of miniarray
		lar = Math.max(...ar[i]); //to find the highest value of the four
  		arg.push(lar);//pushes biggest num on arg
  	}
  	return arg; //returns arg
}

Or you can just return Math.max (…arr);

function largestOfFour (arr){
    return Math.max (...arr);
}