Is there a better way to do this?
In a Javascript lesson I was supposed to return the largest number from each sub-array. My code passed all the tests except for the one involving a sub-array with all negative numbers. I realized this was because the variable I made had an initial value of 0 (var num = 0). Obviously 0 is larger than any negative number so this didn’t pass.
I ended up changing the value to a very large negative number to insure it would return the correct output in most cases. However, I am wondering if there is a way to assign the variable a value of all numbers so this code could provide the proper output given any numbers without being limited by my large negative value?
Here is my code below:
function largestOfFour(arr) {
var numArr = [];
for(let a = 0; a < arr.length; a++) {
var num = -1000000000000;
for(let b = 0; b < arr[a].length; b++) {
if(num < arr[a][b]) {
num = arr[a][b];
}
}
numArr.push(num);
}
return numArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);