Return Largest Numbers in Arrays-negatives

Return Largest Numbers in Arrays-negatives
0

#1

Tell us what’s happening:
Dont know how to deal with the array fill with negative numbers. My code works for all the other arrays:

largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3].
How do i find the biggest out of negative numbers since my max was set to 0 hence it would not be able to work for the negative array?

Your code so far


function largestOfFour(arr) {
  // You can do this!
  var newA = [];
  var max;
  for(let i = 0; i < arr.length; i++){
   max = arr[i].length;
      for(let j = 0; j < arr[i].length; j++){
        if(arr[i][j] > max){
           max = arr[i][j];
        }
      }
    newA.push(max);
  }
console.log(newA);


  return newA;
}

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

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


#2

This is a big problem. Also, your code would not work if the following sub array of positive numbers was encountered.

[1, 1, 1, 1, 1];

Your function would return [5], when it should return [1].


#3

how is it a big problem and how would it not work?


#4

You said in your original post that you assign max to zero, but you actually are initializing max to 4 inside the outer for loop. That is the problem of why your function would return [5] for the sub array of [1, 1, 1, 1, 1] instead of [1].


#5

how would it return 5? 1 is not greater than 4. Where did the 5 come from?


#6

As I already said in my first reply, it is because of the following line of your code.

max = arr[i].length;

You are setting max to be equal to the length of the current sub array being iterated over in arr. My example assumes you call the largestofFour with something like:

largestOfFour( [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4] ]]); // returns [5, 5, 5, 5] instead of [1, 2, 3, 4].

Why should it return [1, 2, 3, 4]? Because the largest number in the 1st sub array is 1, the largest number in the 2nd sub array is 2, the largest number in the 3rd sub array is 3, and the largest number in the 4th sub array is 4.