js obtaining maximum / minimum values in an array

Foreword

We often in the development process, the need to obtain maximum or minimum array, can be considered from the following aspects:

  1. Use Math.max(), Math.min()method
  2. After ordering, obtaining maximum / minimum

Let's see, how to get the maximum value of the following array (similar to obtain minimum):

let arr = [1, 2, 5, 8, 10, 100, -1]

1. Static method Math max / min

Math.max()Function returns the maximum value for a given number of groups.
Its syntax: Math.max(value1[, value2, ...])
Using this method, you need to pay attention to, if no arguments, then return -Infinity. If any of the parameters can not be converted to a numerical value, it is returned NaN.

1.1 ES6 binding using extended operator ...

Extended operator, it can be converted to an array of parameter comma.

Math.max(...arr) 

1.2 binding apply / call method using

Using the apply()method of the first parameter may change this point, the second parameter is an array, to complete the requirements.

Math.max.apply(null, arr) 

Since the apply()method can be used, then we can use the call()method, and with the expansion of operator use.

Math.max.call(null, ...arr) 

1.3 combine to reduce the use of

reduce()The method of receiving a function as an accumulator, a value of each of the array (left to right) started to shrink, as a final calculated value.
Syntax: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Here, the accumulator function is to getMax()compare two numbers and returns the highest value, through this reduction, and finally returns the maximum value of the entire array.

function getMax(prev, next) {
    return Math.max(prev, next)
}
arr.reduce(getMax)

2. Sort acquisition

Compare to find the maximum value of 2.1

It assumes that the first element of the array of maximum value max, loop through the array, do the max with other elements relatively large value is assigned to max. After the end of the cycle, the value of max is the maximum value.

let max = arr[0]
arr.forEach(item => max = item > max ? item : max)
console.log(max) // 100

2.2 will have to sort the entire array to obtain the maximum value

Using the array.sort()method specified sorting function to sort the array. Of course, you can also use other sort, to sort the array.

let AS = arr.sort((a, b) => a - b) 
AS[arr.length-1]  // 获取最大值:100
AS[0] // 获取最小值: -1

The browser runs results

Get the maximum array

[Finish]

Guess you like

Origin www.cnblogs.com/weiqinl/p/10945596.html