I have this little script that will return the largest number of an array, it works, except it doesn't work for multidimensional arrays.
How can I tweak this to return an array of the largest numbers within a multidimensional array?
Source:
function largestOfFour(arr) {
for(var x=0;x < arr.length; x++){
var largest = Math.max.apply(Math, arr[x]);
return largest;
}
}
Example:
> function largestOfFour(arr) {
... for(var x=0;x < arr.length; x++){
..... var largest = Math.max.apply(Math, arr[x]);
..... return largest;
..... }
... }
undefined
> largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
5
>
Expected output:
[5, 27, 39, 1001]
Just map the result of the single results.
function largestOfFour(array) {
return array.map(function (a) {
return Math.max.apply(null, a);
});
}
var largest = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
document.write('<pre>' + JSON.stringify(largest, 0, 4) + '</pre>');
The above mentioned (@Tushar) short version
function largestOfFour(array) {
return array.map(Math.max.apply.bind(Math.max, null));
}
var largest = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
document.write('<pre>' + JSON.stringify(largest, 0, 4) + '</pre>');
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments