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

A brief discussion on the specific use of viewport in mobile terminals

Table of contents 1. Basic Concepts 1.1 Two kinds...

MySQL data aggregation and grouping

We often need to summarize data without actually ...

How to update Ubuntu 20.04 LTS on Windows 10

April 23, 2020, Today, Ubuntu 20.04 on Windows al...

Sample code for implementing markdown automatic numbering with pure CSS

The origin of the problem The first time I paid a...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

Detailed explanation of the use of Vue image drag and drop zoom component

The specific usage of the Vue image drag and drop...

MySQL 5.7.24 installation and configuration graphic tutorial

This article shares the installation and configur...

Using react-beautiful-dnd to implement drag and drop between lists

Table of contents Why choose react-beautiful-dnd ...

How to use ElementUI pagination component Pagination in Vue

The use of ElementUI paging component Pagination ...

JS canvas realizes the functions of drawing board and signature board

This article shares the specific code of JS canva...

A simple method to be compatible with IE6's min-width and min-height

If a website is widescreen, you drag the browser ...