JavaScript finding the largest integer in an array of arrays

后端 未结 5 419
独厮守ぢ
独厮守ぢ 2021-01-23 21:30
function largestOfFour(arr) {
    var newArray = [];
    for(var i =0; i <=arr.length-1; i++){
        console.log(arr[i]);
        newArray[i] = Math.max(arr[i]);
           


        
相关标签:
5条回答
  • 2021-01-23 21:57

    Using lodash

    var x = ([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
    _.flatten(x).max();
    
    0 讨论(0)
  • 2021-01-23 21:58

    You are passing an array to Math.max and expect it to return the maximum in that array.

    However, Math.max returns the maximum among its arguments. So use

    var newArray = [];
    for(var i =0; i < arr.length; ++i)
      newArray[i] = Math.max.apply(void 0, arr[i]);
    

    In ES6, you can use arrow functions and the spread operator to simplify:

    arr.map(a => Math.max(...a));
    
    0 讨论(0)
  • 2021-01-23 22:03

    It won't work like that. Math.max expect separate numbers. You can get desired output using apply

    function largestOfFour(arr) {
        return arr.map(function(subArr){
            return Math.max.apply(Math, subArr);
        });
    }
    
    0 讨论(0)
  • 2021-01-23 22:03

    If you want the ultimate max do this.

    var original = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
    Math.max.apply(null, original.map(function(arr) { return Math.max.apply(null, arr); }));
    

    or if you want a the max of each array just do

    original.map(function(arr) { return Math.max.apply(null, arr); });
    
    0 讨论(0)
  • 2021-01-23 22:13

    Edited: In order to add values to the array, I'd suggest using the push methodn. As in: NewArray.push(Math.max(...sub[i])); or newarray.push(math.max.apply(null, sub[i]). An alternative is alocating, when declarating the array, the size it will take: Var newArray = new Array(arr.length); There's this new spread operator (...) in javascript !

    0 讨论(0)
提交回复
热议问题