Return Largest Numbers in Arrays. Please Help!

function largestOfFour(arr) {
var results = [];
for(var i =0; i<=arr.length; i++){

var temp = arr[i].sort().reverse()[0];
results[i] = temp;

}
return results;
}

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

Im getting a Cannot read property ‘sort’ of undefined" or Cannot read property ‘reverse’ of undefined". Please Help!

As a hint: remember that in order to iterate through the actual numbers, you need to use two for loops. You are working with a 2D array.

Also instead of results[i] use results.push(temp), it will be less confusing.

But if you want to continue that way, then use arr[i] not arr[0] because you want to check every array. And you are getting that error because of the condition in your for loop. Set it to i<arr.length instead.

good luck

hi Thanks for reply. Yeah i meant arr[i] not arr[0]. that was a typo.

But with I’m still getting cant read property sort error

Set it to i<arr.length instead. The last iteration is going through an index that doesn’t exist, that’s why.

thanks for helping, you are correct!

Here’s my final correct answer!

function largestOfFour(arr) {
var results = [];
for(var i =0; i < arr.length; i++){

var temp = arr[i].sort(function(a,b){return a-b;}).reverse()[0];
results.push(temp);

}
return results;
}

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

1 Like