6 ways to implement the maximum and minimum values ​​of an array in javascript

6 ways to implement the maximum and minimum values ​​of an array in javascript

Given an array [1,8,5,4,3,9,2], write an algorithm to get the maximum value 9 and the minimum value 1 of the array.

1. Extend the min() and max() functions through the prototype property

The idea of ​​Algorithm 1 is to find the result by comparing the first value with the subsequent values ​​in a loop in the custom min() and max() functions, and dynamically updating the maximum and minimum values.

        // minimum value Array.prototype.min = function () {
            let min = this[0];
            let len ​​= this.length;
            for (let i = 1; i < len; i++) {
                if (this[i] < min) min = this[i]
            }
            return min
        }
        // Maximum value Array.prototype.max = function () {
            let max = this[0];
            let len ​​= this.length;
            for (let i = 1; i < len; i++) {
                if (this[i] > max) max = this[i]
            }
            return max
        }
        // Result console.log(arr.min()); // 1
        console.log(arr.max()); // 9

2. Use the min() and max() functions of the Math object

The main idea of ​​Algorithm 2 is to change the execution body of the function through the apply() function and pass the array as a parameter to the apply() function. In this way, the array can directly call the min() and max() functions of the Math object to get the return value.

        Array.min = function(array) {
            return Math.min.apply(Math, array)
        }
        // Maximum value Array.max = function (array) {
            return Math.max.apply(Math, array)
        }
        // Result console.log(Array.min(arr)); // 1
        console.log(Array.max(arr)); // 9

3. Optimization of Algorithm 2

In Algorithm 2, the min() function and the max() function are used as static functions of the Array type, but chain calls are not supported. We can use object literals to simplify them.

        // minimum value Array.prototype.min = function() {
            return Math.min.apply({}, this)
        }
        // Maximum value Array.prototype.max = function () {
            return Math.max.apply({}, this)
        }
        // Result console.log(arr.min()); // 1
        console.log(arr.max()); // 9

Different from Algorithm 2, during verification, since the min() function and the max() function are instance methods, they can be called directly through the array.
In the above algorithm code, the first value passed to the apply() function is {}, which actually represents the global object of the current execution environment. The second parameter this points to the array that needs to be processed.
Due to the particularity of the apply function, the first parameter will be automatically replaced with a pointer to the global object when it is specified as null or undefined, and the original value will be wrapped. So we can also set the first parameter to null, undefined.

4. Using the reduce() function of Array type

The main idea of ​​Algorithm 4 is that the reduce() function does not set the initialValue, but directly uses the first element of the array as the first parameter of the callback function and compares it with the subsequent values ​​in turn. When the maximum value needs to be found, the accumulator returns the larger value in each round; when the minimum value needs to be found, the accumulator returns the smaller value in each round.

        // minimum value Array.prototype.min = function () {
            return this.reduce((pre, cur) => {
                return pre < cur ? pre : cur
            })
        }
        // Maximum value Array.prototype.max = function () {
            return this.reduce((pre, cur) => {
                return pre > cur ? pre : cur
            })
        }
        // Result console.log(arr.min()); // 1
        console.log(arr.max()); // 9

5. Use the sort() function of Array type

The main idea of ​​Algorithm 5 is to sort the array with the help of the array's native sort() function. After the sorting is completed, the first and last elements are the minimum and maximum elements of the array.
The default sort() function sorts in alphabetical order, and numbers are treated as strings. For example, the number 18 will be treated as "18", and the number 6 will be treated as "6". When sorting, the comparison is based on each bit of the string. Because "1" is smaller than "6", "11" will be smaller than "6" when sorting. For arrays of numeric types, this is obviously unreasonable. So we need to do a custom sort.

        let sortArr = arr.sort((a, b) => a - b)
        // Minimum value sortArr[0]
        // Maximum value sortArr[sortArr.length - 1]
        // Result console.log(sortArr[0]); // 1
        console.log(sortArr[sortArr.length - 1]); // 9

6. Use ES6's spread operator

        // Minimum value Math.min(...arr)
        // Maximum value Math.max(...arr)
        // Result console.log(Math.min(...arr)); // 1
        console.log(Math.max(...arr)); // 9

This concludes this article about 6 ways to implement maximum and minimum values ​​of an array in javascript. For more relevant content about maximum and minimum values ​​of javascript arrays, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • An example of how to traverse and find the maximum and minimum values ​​in an array in JavaScript
  • JS implementation example of getting the maximum or minimum value in an array
  • Four methods to find the maximum and minimum values ​​of js arrays
  • Solution to the maximum and minimum values ​​in an array and their output in the following table in JavaScript
  • JavaScript learning notes: Get the maximum and minimum values ​​in an array
  • Javascript method summary of obtaining the maximum and minimum values ​​in an array
  • How to get the maximum value, minimum value and length of an array in JS
  • How to get the maximum and minimum values ​​of an array in JavaScript
  • How to get the minimum and maximum values ​​of an array in JavaScript

<<:  Detailed graphic description of the database installation process of MySQL version 5.7.24

>>:  CentOS6.8 Chinese/English environment switching tutorial diagram

Recommend

Vue method to verify whether the username is available

This article example shares the specific code of ...

How to use Celery and Docker to handle periodic tasks in Django

As you build and scale your Django applications, ...

Several common methods of sending requests using axios in React

Table of contents Install and introduce axios dep...

Vue3 slot usage summary

Table of contents 1. Introduction to v-slot 2. An...

Solution to the problem of adaptive height and width of css display table

Definition and Usage The display property specifi...

Windows 2016 Server Security Settings

Table of contents System update configuration Cha...

Use CSS variables to achieve cool and amazing floating effects

Recently, I found a fun hover animation from the ...

The difference between hash mode and history mode in vue-router

vue-router has two modes hash mode History mode 1...

Solve the problem of Docker starting Elasticsearch7.x and reporting an error

Using the Docker run command docker run -d -p 920...

Detailed steps for installing Tomcat, MySQL and Redis with Docker

Table of contents Install Tomcat with Docker Use ...

W3C Tutorial (13): W3C WSDL Activities

Web Services are concerned with application-to-ap...