Return Largest Numbers in Arrays for negative integers

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.

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

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

1 Like

You declare let biggest = 0, your negative numbers will never be bigger than 0. Maybe you want to start with biggest at something else

1 Like

You could set biggest to first index in the arr and then compare from there. Rather than hardcode it to 0.

1 Like

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.

Actually there are people saying the opposite. There maybe little to no harm done, but you can read about that here.

1 Like

Fascinating. Thanks for the link!

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.

1 Like

Makes sense. Thanks.