/ function largestOfFour(arr) {
// You can do this!
var largestFour = [];
for (var i = 0; i < arr.length; i++) {
var largestThis = 0;
for (var j = 0; j < arr.length; j++) {
if ((arr[i][j]) > largestThis) {
largestThis = (arr[i][j]);
Seems pretty similar to what I was thinking; if it works, it works. I’m not sure what the ‘ideal’ or ‘suggested’ solution is, if one exists, but here’s my spin on it.
function largestOfFour(arr) {
// You can do this!
var outarr = [];
var topnum = 0;
for (i = 0; i < arr.length; i++) {
topnum = 0;
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > topnum) {
topnum = arr[i][j];
}
}
outarr[i] = topnum;
}
return outarr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Though now that I look back on it, shame on me for not camelCasingMyVariableNames.
I’m not savvy enough yet to know if there’s a significant efficiency difference between .push() and direct assignment, or if there are other problems either method might introduce that the other one doesn’t. If someone knows, though, I’d sure be interested in hearing.
EDIT: Just noticed OP’s second for loop is using arr.length and not arr[i].length. For the purposes of the exercise it doesn’t matter, since arr.length and arr[i].length are always equal to 4 - but if any of the sub-arrays had lengths differing from the main array, it’d break. (I think.)
function max(arr) {
return arr.reduce(function(old, cur){
return old>cur ? old : cur;
}, arr[0]);
}
function largestOfFour(arr) {
// You can do this!
return arr.map(max);
}
function largestOfFour(arr) {
// You can do this!
var result = [];
for (var ai = 0; ai < arr.length; ai++) {
result.push(largest(arr[ai]));
}
return result;
}
function largest(arr) {
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
There’s a solution which uses only the array’s .map method, and I was dumbfounded when I found out it exists it. Here goes:
function largestOfFour(arr) {
return arr.map(a => Math.max.apply(null, a));
}