Need help figuring this out (Return Largest Numbers in Arrays)

Need help figuring this out (Return Largest Numbers in Arrays)
0.0 0

#1

This is my code. I know that it’s wrong. Can someone help me with it?

function largestOfFour(arr) {
// You can do this!
var largestOfFour = ([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
arr.sort(function(a,b){
return b-a;

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


#3

like this?

function largestOfFour(arr) {
// You can do this!
var largestOfFour = ([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
arr.reduce(function(a,b){
return b-a;

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


#4

I think you need to sort each sub-array, not the array of arrays. I don’t see that reflected in your code.


#5

How do you sort each sub array?


#6

I created a sub-array variable and moved each sub-array into it in turn using a for loop.


#7

Also, I used sort to solve this one as well, so it will work, but I think my code is less than elegant :slight_smile: I looked up reduce and you might want to try P1xt’s way.

On the sub-arrays: I was able to run the array through a for loop, then set each sub-array by remembering that the first sub-array is actually arr[0], the second sub-array is arr[1] etc…

Hope that helps :slight_smile:


#8

Do you think that this works?

function largestOfFour(arr) {
// You can do this!
var largestOfFour = [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1];
var arr=[];
for(var i = 1001; i > 0; i–) {
arr.sort(function(a, b) {
return b-a;
});
}
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


#9

A problem I see is that you are creating a variable called largestOfFour and setting the array values within your function and this won’t work in the long term. Since arr is the parameter being fed in, use that to hold your original array. You don’t need to set it, it comes pre-filled :slight_smile:

Use a for loop to iterate through arr using arr.length and set a sub-array variable to equal each sub-array (which are arr[0], arr[1], arr[2], arr[3]).