Methods for getting the maximum value from a two-dimensional array in JS _ javascript tips

Source: Internet
Author: User
This article introduces three solutions for getting the maximum value of a two-dimensional array in JavaScript. The introduction is very detailed and has reference value. In JavaScript, you can use the built-in maximum value of Math. max (), but it is still difficult to retrieve the maximum value from multiple arrays.

Problem description

Suppose you have an array that contains a subarray of numbers, and what we need to do is to return the maximum number from each subarray in the array.

Basic Solution

Function largestOfFour (arr) {var results = []; // create a results variable to store the results. // create an outer loop and traverse the outer array for (var n = 0; n <arr. length; n ++) {var largestNumber = 0; // create the second variable, store the maximum number // create another loop, traverse the sub-array for (var sb = 0; sb <arr [n]. length; sb ++) {// check whether the element of the sub-array is greater than the maximum value currently stored. if (arr [n] [sb]> largestNumber) {// if true, assign this value to the variable largestNumberlargestNumber = arr [n] [sb] ;}// after an internal loop, save the values in each sub-array to the results array. results [n] = largestNumber;} // return the array return results;} largestOfFour ([[], [, 2, 44, 234], [4567,1, 34,456,456, 6], [,]); // [7, 78]

The above method is a common solution, traversing the array and its sub-array through two for loops:

Create a results variable to store the maximum value retrieved from each sub-array.

Create an External Loop for traversing the outer Array

Create the second variable largestNumber to store the maximum value. This variable value must be placed outside the internal for loop, because it will not be reassigned.

Create a second for loop to traverse each element in the Child Array

Use an if statement to determine whether the element of the current sub-array is greater than the maximum largestNumber currently stored. If it is (true), store the maximum value to largestNumber.

After the internal loop ends, store the maximum value in each sub-array to the originally declared variable results.

Returns the results array.

After each maximum value of all sub-arrays is obtained, a new array results is obtained:

Array.prototype.max = function () {return Math.max.apply({},this);}largestOfFour(arr).max();

The maximum value is obtained.

largestOfFour([[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]]).max(); // 4567

Intermediate solution

Function largestOfFour (arr) {// use the map () method and the callback function to combine the maximum values in the subarray to obtain the return arr array. map (function (group) {// return the maximum value of each sub-array to the return group in the group array through the reduce method. reduce (function (prev, current) {// if current is greater than prev, current is returned; otherwise, prevreturn (current> prev) is returned )? Current: prev ;}) ;}largestoffour ([[234], [, 2,], [,], [, 6], [, 78, 34,456,456]); // [7, 78]

Use Array. prototype. map () to traverse the Array in the outer Array. When the map () method is used to traverse the array, a callback function is called. In this callback function, the reduce () method is used to merge each sub-array group, returns the value to a new array. When using the reduce () method, a callback function is also called. This callback function only performs one thing, that is, the elements in the sub-array are compared. If current is greater than prev, current is returned. Otherwise, prev is returned, and the maximum value in each sub-array is obtained.

As before, Math. max. apply () is used to obtain the maximum value.

Best Solution

function largestOfFour (arr) {return arr.map(Function.apply.bind(Math.max, null));}largestOfFour([[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]]); //[34, 456, 4567, 78]

This solution uses Function. the bind method creates a special callback function, which is similar to Math. the max method is the same, but it has a Function. prototype. the apply function uses an array as its parameter.

Traverse each element in the primary array, that is, each sub-array in the array.

The map () method requires a callback function to find the maximum value in each array. You need to create a function so that Math. max can accept the input array. In other words, this is very simple and it works very well, such as Math. max ([,]); will return a maximum of 43

Function. prototype. The apply method can accept arrays as parameters, but the Function calls context, which is a bit complicated. For example, Math. max. apply (null, [9, 43, 20, 6]) will call a Max. max method, but this method is not easy to find.

Here, a null parameter is passed to Function. prototype. apply, indicating that Math. max does not need any context.

Because arr. map () requires a callback Function, not just an expression, we provide a Function in the Function. bind method.

Because Function. prototype. apply is a static method, similar to a Function object, we can call it Function. prototype. apply bound to a Function. prototype. bind. Example: Function. apply. bind

Now you can use the Function. prototype. apply. bind callback Function to specify the context. For example, in this example, the Math. max Method

Because it is embedded in the Function. prototype. apply method, a context is required as the first parameter, and the context is still false.

Therefore, we pass null as the second parameter to Function. prototype. apply. bind, and bind a context. This context is the Math. max method.

Because Math. max is independent from any context, it ignores the false context of Function. prototype. apply method calls.

We use Function. prototype. apply. bind (Math. max, null) to make a new Function accept the value of arr. map, such as the sub-array in the array.

Obtain the maximum value from a multi-dimensional array.

The above uses different methods to retrieve the maximum values in the sub-array from the two-dimensional array, and re-forms the maximum values into a new array. if you extend the maximum value, you also need to use Array. prototype. max function, which uses Math. max. apply ({}, this) to obtain the maximum value. However, if it is not a two-dimensional array, the above method will not be able to retrieve the maximum value in the array.

To obtain the maximum value in a multi-dimensional array, you can combine the join () and split () methods:

function largestOfFour (arr) {var newArray = arr.join(",").split(",");return Math.max.apply({},newArray);}largestOfFour([12,23]); // =>23largestOfFour([12,23,[1234,324],[345,566]]); // =>1234largestOfFour([12,23,[1234,324,[23121,90890]],[345,566,[345,78,90]]]); // =>90890largestOfFour([12,23,[1234,324,[23121,90890]],[345,566,[345,78,90,[90909090,988]]]]); // =>90909090

Similarly, you can use a similar method to obtain the minimum value in a multi-dimensional array:

function smallerOfFour (arr) {var newArray = arr.join(",").split(",");return Math.min.apply({},newArray);}smallerOfFour([12,23]); // =>12smallerOfFour([112,23,[1234,324],[345,566]]); // =>23smallerOfFour([212,123,[1234,324,[23121,90890]],[345,566,[345,78,90]]]); // =>78smallerOfFour([102,230,[1234,324,[23121,90890]],[345,566,[345,78,90,[90909090,988]]]]); // =>78

Summary

The document "JavaScript Study Notes: getting the maximum and minimum values in an array" describes how to use Math. max. apply ({}, arr) to obtain the maximum number in an array. This article describes how to retrieve the maximum number of two-dimensional arrays from different perspectives. However, in many cases, arrays also contain multi-dimensional arrays, the article finally introduces how to retrieve the maximum value from a multi-dimensional array. If you have more solutions, please share them with us in your comments.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.