1

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]
13aal
  • 1,634
  • 1
  • 21
  • 47

2 Answers2

2

You can use ES6 arrow function and spread operator.

arr.map(e => Math.max(...e))

map will iterate(i.e. nested arrays) over all the elements of main array and Math.max(...e) will return the max element of that array. The ...e will pass the elements of e array individually to the max().

var arr = [ [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1] ]

var res = arr.map(e => Math.max(...e))

document.write(res);
Tushar
  • 85,780
  • 21
  • 159
  • 179
isvforall
  • 8,768
  • 6
  • 35
  • 50
1

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392