# Basic Algorithm Scripting - Return Largest Numbers in Arrays

I’m having a problem getting the actual function to work.

I’ve gotten the console.log to work in the actual loop and it returns what I want, but the actual function returns arr which is just returning the actual arrays.

I’ve tried assigning arr = Math.max(…arr[i]) but that doesn’t work.

Any hints would be appreciated

``````function largestOfFour(arr) {

for (let i=0; i<arr.length; i++) {
console.log(Math.max(...arr[i]))
}

return arr;
}

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

``````

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

Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays

You aren’t storing this value anywhere. You probably need to put this somewhere so you can build up the output the function needs.

this was what I tried to do but it only returns 5

``````
function largestOfFour(arr) {

for (let i=0; i<arr.length; i++) {
arr = Math.max(...arr[i])
}

return arr;
}

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

``````

This says “clobbler the array `arr` and replace it with the maximum of subarray `i`

Why not put the maximum value somewhere else? `arr` isn’t the only variable you’re allowed to use.

How about creating a new array that you can put the largest of each sub array in and then return the new array?

``````function largestOfFour(arr) {
return arr;
}

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

and I feel like I NEED to return arr and I shouldn’t change the return to anything else or I’m like cheating.

If you don’t see a big comment saying “Only Change …”, then change the guts of the function however you like.

1 Like

Well you can not return `arr` since it is the array of arrays. Regardless of how you feel about it, your only choice is to return a new array by iterating through `arr`, capturing the largest of each sub array in the new array, and then returning the new array.

1 Like

Thank you both, I guess I’m making things harder for myself.

I just see these algorithm problems as having a specific way they want you to solve it which is why they added that “return arr” in the starter code. It throws me off big time and I’ve been trying to work these problems out without trying to change the return.

I guess I should stop doing that

That made things so much easier, Thanks again.

Some of the JavaScript teaching challenges would sometimes force you into a specific way of completing them. However, all of the algorithm challenges allow you to solve them any way you want as long as you meet the challenge requirements and pass the tests.