HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Create an array with the highest values from each array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theeachcreatearraywithhighestvaluesfrom

Problem

I am working my way through FreeCodeCamp's Javascript challenges and Return Largest Numbers in Arrays took me a minute. In this one the goal was to create an array with the highest values from each array as its elements.

I am currently using for loops to iterate through the various arrays and arrays of arrays. I wanted to see if there was a better way to do this challenge.



function largestOfFour(arr) {
// You can do this!
var largestNum = 0;
var newArray = [];
for(var i = 0; i largestNum){
largestNum = a;
newArray[i] = largestNum;
}
}
largestNum=0;
}
console.log('complete Test' + newArray);
return newArray;
}

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

Solution

The challenge says that you will be given exactly four subarrays, but it doesn't specify the length of each subarray. You've assumed a square matrix, which is not stated in the problem.

To find the maximum of 4, 5, 1, and 3, you could write Math.max(4, 5, 1, 3). If those numbers are given to you as an array, you could use Math.max.apply(null, array).

To transform each element of the outer array, use arr.map().



function largestOfFour(arr) {
return arr.map(function(subArr) {
return Math.max.apply(null, subArr);
});
}

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

Context

StackExchange Code Review Q#132002, answer score: 7

Revisions (0)

No revisions yet.