Returning Largest Number in Arrays - Code Improvements

Returning Largest Number in Arrays - Code Improvements
0.0 0


Hi All, I just want some suggestion on how to improve my code. This is for Returning Largest Number in Arrays challenge. Please see below code.

function largestOfFour(arr) {
// You can do this!
var newArray = [];
for (var a = 0; a < arr.length; a++){
arr[a].sort(function(a, b){
return b - a;
newArray[a] = arr[a][0];

return newArray;

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

Thank you!


Hey there! I think the code looks just fine. :slight_smile:

The only comment I have is how you populate newArrary—I’m not entirely sure if it’s common practice to specify the index of a position that does not exist to be populated. I’m sure someone with more experience can comment on that!

For future reference, you could also use push():


Depending on how you sort your list, you could also use pop() or shift()—although do keep in mind that they do change the original array.


Hey ewojjowe,

Here is my solution:

function largestOfFour(arr) {
  var myArr = [];
	for (let i of arr) {
		myArr.push(Math.max.apply(null, i));
  return myArr;

Reference to the Math object

PS - not in any way saying my code is better, just another prospective :slight_smile:



Here is a pure functional one-liner version using latest E6 features such as arrow functions and spread operator:

function largestOfFour_v2(arr){return>Math.max(…a));}



Thank you for that. Very helpful! :slight_smile: