Tell us what’s happening:
Here is the algorithm I have come up with. It does what I wanted it to do but I didn’t take into account the fact that it only works for positive integers. Now I’m a little stuck on how to refactor this so it works on all test cases without having to try a completely different approach. Any suggestions?
Your code so far
function largestOfFour(arr) {
// You can do this!
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let biggest = 0;
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] > biggest) {
biggest = arr[i][j];
};
}; newArr.push(biggest);
};
return newArr;
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.
You can use either Number.NEGATIVE_INFINITY (a constant, not overwritable) or -Infinity (a property of window and is overwritable) in this case. Also it’s best to avoid declaring variables inside loops
Thanks. I had the variable outside originally but the code wasn’t working so I think I had moved it there just to see if that would effect anything and then just neglected to move it back after I made some other changes. So let me ask you though, why is it best to not declare variables inside loops?
Thanks. After asking I did some more searching and it appeared that would be my best course, and your reply confirmed it. Works like a charm, thanks again.
If you declare the variable inside a loop it will be redeclared each iteration, so it will erase any data you saved in it. Thats in cases you need a variable to store some data in while iterating.