Getting the min and max value in JavaScript, but from a 2D array

后端 未结 9 1405
再見小時候
再見小時候 2021-01-13 04:32

I know this gets asked again and again but hear me out - this question is slightly different.

I can get a max or min from a 1D array like this:

var          


        
相关标签:
9条回答
  • 2021-01-13 04:43
    var list = [
      [1, 112.0],
      [2, 5.12],
      [3, 113.1],
      [4, 33.6],
      [5, 85.9],
      [6, 219.9]
    ];
    
    function getMinMax(list) {
    
      var min = +Infinity;
      var max = -Infinity;
    
      for (var i = 0; i < list.length; i++) {
        var touple = list[i];
    
        var val = touple[1];
        console.log(touple);
        console.log(val);
    
        min = Math.min(min, val);
        max = Math.max(max, val);
      }
    
      return {
        min: min,
        max: max
      };
    
    }
    
    console.log(getMinMax(list));
    
    0 讨论(0)
  • 2021-01-13 04:52

    If you are saying it is 2D array then it should have one less []

    var myArray = [[1, 112.0],[2,5.12],[3,113.1],[4,33.6],[5,85.9],[6,219.9]];
    var w_max=+Infinity;
    var w_min=-Infinity;
    
    for(var i=0;i< myArray.length;i++){
        elementArray = myArray[i];
        if(w_max < Math.max.apply(Math, elementArray)){
            w_max = Math.max.apply(Math, elementArray);
        } 
        if (w_min > Math.min.apply(Math, elementArray)){
            w_min = Math.min.apply(Math, elementArray);
            }
    }
    
    0 讨论(0)
  • 2021-01-13 04:52

    The first answer is not correct!!!

    let arr = [[1, 112.0],[2,5.12],[3,113.1],[4,33.6],[5,85.9],[6,219.9]];
    let values = Array.concat.apply([],arr);
    let max = Math.max(...values);
    let min = Math.min(...values);
    console.log(arr)
    console.log(min)//1
    console.log(max)//219.9
    console.log(values)//[ 1, 112, 2, 5.12, 3, 113.1, 4, 33.6, 5, 85.9, 6, 219.9 ]
    
    0 讨论(0)
提交回复
热议问题