Find the min/max element of an Array in JavaScript

前端 未结 30 2064
無奈伤痛
無奈伤痛 2020-11-21 06:18

How can I easily obtain the min or max element of a JavaScript Array?

Example Psuedocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max()         


        
30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 06:57

    I thought I'd share my simple and easy to understand solution.

    For the min:

    var arr = [3, 4, 12, 1, 0, 5];
    var min = arr[0];
    for (var k = 1; k < arr.length; k++) {
      if (arr[k] < min) {
        min = arr[k];
      }
    }
    console.log("Min is: " + min);

    And for the max:

    var arr = [3, 4, 12, 1, 0, 5];
    var max = arr[0];
    for (var k = 1; k < arr.length; k++) {
      if (arr[k] > max) {
        max = arr[k];
      }
    }
    console.log("Max is: " + max);

提交回复
热议问题