4
function largestOfFour(arr) {
 for(var i = 0; i < arr.length; i++) {
 var largest = Math.max.apply(Math, arr[i]);
 return largest;
 }
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

I need to return the largest number from each erray. When I run my code with console.log, it prints out the largest number of each array but when i return it, only the largest number from array 0 returns. Can anyone help me with this?

asked Apr 30, 2015 at 19:54

3 Answers 3

5

return exits the function, you need to create an array and add the largest values to it.

function largestOfFour(arr) {
 var result = [];
 for (var i = 0; i < arr.length; i++) {
 result.push(Math.max.apply(Math, arr[i]));
 }
 return result;
}
document.body.innerHTML = largestOfFour([
 [4, 5, 1, 3],
 [13, 27, 18, 26],
 [32, 35, 37, 39],
 [1000, 1001, 857, 1]
]);

answered Apr 30, 2015 at 19:56
0
1

You can also use map instead of for

function largestOfFour(arrs) {
 return arrs.map(function(arr){
 return Math.max.apply(null, arr);
 });
}
document.body.innerHTML = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

answered Apr 30, 2015 at 20:08
0

Another way is to use Array.prototype.reduce()

function largestOfFour(arr) {
 return arr.reduce(function(p, c, index, arr){
 p.push(Math.max.apply(null, c));
 return p;
 }, []);
}
answered Apr 30, 2015 at 20:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.