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
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
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
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
lang-js