Max value of a multidimensional array javascript

前端 未结 7 2322
太阳男子
太阳男子 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:30

    The solution using Array.prototype.push, Math.min and Math.max methods:

    // arr is your initial array
    var flattened = [], minValue, maxValue;
    arr.forEach(function (v) {
        Array.prototype.push.apply(flattened, v);
    });
    
    minValue = Math.min.apply(null, flattened);
    maxValue = Math.max.apply(null, flattened);
    
    console.log('min: ' + minValue, 'max: ' + maxValue);  // min: 1 max: 80.8
    

    DEMO link

提交回复
热议问题