Max value of a multidimensional array javascript

前端 未结 7 2321
太阳男子
太阳男子 2021-02-09 18:35

I have a multidimensional array of x columns and y rows. How can I find the min and the max value of the matrix? Example:

[[1,  37.8, 80.8, 41.8],
[2,  30.9, 69.         


        
7条回答
  •  囚心锁ツ
    2021-02-09 19:26

    Regardless of the dimension of the array, i believe this is the way to get the max of all primitives involved.

    function getMax(a){
      return Math.max(...a.map(e => Array.isArray(e) ? getMax(e) : e));
    }
    
    var arr = [[1,  37.8, 80.8, 41.8],
               [2,  30.9, 69.5, 32.4],
               [3,  25.4,   57, 25.7],
               [4,  11.7, 18.8, 10.5],
               [5,  11.9, 17.6, 10.4],
               [6,   8.8, 13.6,  7.7],
               [7,   7.6, 12.3,  9.6],
               [8,  12.3, 29.2, 10.6],
               [9,  16.9, 42.9, 14.8],
               [10, 12.8, 30.9, 11.6],
               [11,  5.3,  7.9,  4.7],
               [12,  6.6,  8.4,  5.2],
               [13,  4.8,  6.3,  3.6],
               [14,  4.2,  6.2,  3.4]];
     console.log(getMax(arr));

    It should work on arrays with indefinite dimension.

    function getMax(a){
      return Math.max(...a.map(e => Array.isArray(e) ? getMax(e) : e));
    }
    
    var arr = [[1,  37.8, 80.8, 41.8],
               [2,  30.9, 69.5, 32.4],
               [3,  25.4,   57, 25.7],
               [4,  11.7, 18.8, 10.5],
               [5,  11.9, 17.6, 10.4],
               [6,   8.8, 13.6,  7.7],
               [7,   7.6, 12.3,  9.6],
               [8,  12.3, 29.2, 10.6],
               [9,  16.9, 42.9, 14.8],
               [10, 12.8, 30.9, 11.6],
               [11,  5.3,  [6.1,[56.7,[98.55]]],  4.7],
               [12,  6.6,  8.4,  5.2],
               [13,  4.8,  6.3,  3.6],
               [14,  4.2,  6.2,  3.4]];
     console.log(getMax(arr));

提交回复
热议问题