Return Largest Numbers in Arrays: can't reproduce the simplest solution into the loop

Tell us what’s happening:

When I tried this

function largestOfFour(arr) {
  let x, y = []
  
    x = arr.shift()
    console.log(x)// returns 4,5,1,3
    y = Math.max(...x)
    console.log(y)//returns 5

    x = arr.shift()
    console.log(x)// return 13,27,18,26
    y = Math.max(...x)
    console.log(y)//return 27

//etc.

  return arr;
}

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

It prints the largest number of one array. But when I put this into a loop. It returns “-Infinity”
Your code so far


function largestOfFour(arr) {
  let x, y = []
  for (let i = 0; i < arr.length; i++){
   x = arr[i].shift()
   y = Math.max(...x)
  }
  console.log(y)
  
  return y;
}

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


/**  x = arr.shift()
    console.log(x)
    y = Math.max(...x)
    console.log(y) */

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 OPR/62.0.3331.119.

Link to the challenge:

try looking st what happens in your code using the JavaScript Tutor
look at the value each variable get, is the value you expect?

I was expecting at the first iteration that x = [4, 5, 1, 3]. But it seems that is equal to 4. Due to that the following line doesn’t do anything.

you may want to check what shift does and on what array you used it on

shift takes the 1st element of an array (changing the array). I wanted to applied to each element of the main array intending to then apply Math.max to each of those elements (like if [4, 5, 1, 3] was going to return 5).

Finally, I landed this:

function largestOfFour(arr) {
  let x, y, z = []
  for (let i = 0; i < arr.length; i++){
   x = arr[i]
   y = Math.max(...x)
   z.push(y)     
  }
  return z;
}

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

It did work. I haven’t seen the FCC solution. But I think my main problem was that I didn’t realize how to use methods like push to really store the value required from each iteration.

Am I right?

And, about my solution: would it be Procedural or Declarative? Some source to found out the concept?

Hi @leoncpaulo
I find this solution simpler to understand using for-in loop and Math.max() of a spread array:

        function largestOfFour(arr) {
          // You can do this!
          let r = [];
          for (let a in arr){
                r.push(Math.max(...arr[a]));
          }
          return r;
        }
                
        largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

I hope it helps.