Four Methods of Finding the Maximum and Minimum Values of js Array

  • 2021-07-26 06:23:24
  • OfStack

Given the array [54, 65, 43, 21, 12, 34, 45, 58, 97, 24], find its maximum and minimum values?

Defining Array

var ary = [54,65,43,21,12,34,45,58,97,24];

1. String splicing method

The array is converted into string by toString and join, then spliced with max and min of Math, and finally executed eval


var maxN = eval("Math.max(" + ary.toString() + ")");
var minN = eval("Math.min(" + ary.toString() + ")");

Or


var maxN = eval("Math.max(" + ary.join() + ")");
var minN = eval("Math.min(" + ary.join() + ")");

2. Sorting method

First, the array is sorted from small to large, the first array is the minimum value, and the last one is the maximum value


ary.sort(function(a,b){return a-b;});
var minN = ary[0];
var maxN = ary[ary.length-1];

3. Hypothesis method

Assume that the first one in the array is the maximum (or minimum), compare it with the following one, and replace the maximum (or minimum) if the following one is larger than the maximum (or smaller than the minimum)


var maxN = ary[0];
var minN = ary[0];
for(var i=1;i<ary.length;i++){
  var cur = ary[i];
  cur>maxN ? maxN=cur : null;
  cur<minN ? minN=cur : null;
}

4. max and min methods of Math

Use the apply method to make arrays available as passed parameters


var maxN = Math.max.apply(null,ary);
var minN = Math.min.apply(null,ary);

Related articles: