Can we do it this way?Return Largest Numbers in Arrays

Tell us what’s happening:
I just wanted to check if we can do it this way-
instead of making use of subarrays, can we split the given array to get a single array with all numbers, and then return the largest number for every four numbers?
If we can, then can you help me out by guiding me towards the solution?

Your code so far




function largestOfFour(arr) {
  // You can do this!
  var numbers= arr.split(' ');
  var largestNo = 0;
  for(let i=0;i<4;i++){
   if(numbers[i]> largestNo){
     return numbers[i];
   }
  }

  return arr;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; 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

yes, you can.
But you should have two loos. one to iterate through the 4 arrays and one to iterate through each array element.
You should have an variable to keep store every largest number you find and then return that variable.

Though I would recommend solving this exercise using a map() and Math.max(). =)

No what I meant was, convert the subarrays into one single array and then checking for every 4 numbers( not every 4 arrays).
so for ex, first make the above array into this-
[4,5,1,3,13,27,18,26,…,1]
and then check for the first 4
so it will return 5
then it will check the next 4
and return 27
and so on until the last 4 numbers.

Is this possible?

You can, but you would a logic a bit complex - but what happens if you function is suddenly used with an array that have subarray of various lengths?

Example: [[1,4],[14,22,76,6,9],[3,2,1],[1]]

The best thing you can do is find a way to solve it that doesn’t rely on a fixed length of the subarrays or of the array

Yup I know it has limitations, but I’m just curious as to how the code would look.
So, if it isn’t a trouble, then please tell me the code for that.

You can try to engineer it yourself, it would need a bit of work to figure out the exact logic
Like this I would imagine it would need a loop that advance of 4 at a time, with something like Math.max(…arr.slice(i,i+4)) inside, to make it fast. But at that point better just keep the subarrays.
Or Math.max(arr[i], arr[i+1], arr[i+2], arr[i+3])

Or even with two nested for loops but I have no intention of doing that. If you want to see it, you can try to do it yourself

Interesting…
btw thanks