Max value of a multidimensional array javascript

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

    You can also achieve this with a reduction (it's slower but if the array is not huge, it doesn't matter) resulting in a object containing both the min and the max like so:

    matrix.reduce(function (res, item) {
        item.forEach(function (val) {
            if (!res.hasOwnProperty('max') || val > res.max) res.max = val;
            if (!res.hasOwnProperty('min') || val < res.min) res.min = val;
        });
        return res;
    }, {});
    

提交回复
热议问题