I was able to solve this problem with just a for loop, but I need some explanation

I cant explain how this part works : largestNumbers.push(Math.max(…arr[i]));

  **Your code so far**
[spoiler]

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

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

[/spoiler]

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

In each iteration:

...arr[i] // unpack an element (,which itself is an array) of arr, … is the spread sytax
//so for i=0, you get the list: 4, 5, 1, 3
Math.max(...arr[i]) // returns the maximum of the list above, i.e. 5 when i=0
largestNumbers.push(Math.max(...arr[i])); //Add the maximum (i.e. 5 when i=0) returned from the last step to the end of the array called largestNumbers, thus the result.

Hope that helps.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.