The method of taking the maximum value in a two-dimensional array in JS _javascript tips

Source: Internet
Author: User
Tags prev

The maximum value of the built-in Math.max () can be used in JavaScript, but it is still difficult to extract the maximum from a multiple array.

Problem description

Suppose you have an array, and the array contains a substring of numbers, and what we're going to do is return the largest maximum number from each sub array in the array.

Basic Solutions

function Largestoffour (arr) {
var results = [];//Create a results variable to store
//Create an outer loop that iterates through the outer array for
(var n = 0; n < Arr.length; n++) {
var largestnumber = 0;//Create a second variable, store the maximum number
//Create another loop, traverse the child array for
(var sb = 0; sb < arr[n].length; sb++ {//check that the
element of the child array is greater than the current stored maximum if
(ARR[N][SB] > Largestnumber) {
//If True, assign this value to the variable Largestnumber
Largestnumber = ARR[N][SB];
}
After the internal loop, save the value in each child array to the array results
results[n] = largestnumber;
}
Returns an array return
results;
}
Largestoffour ([[[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]]); [34, 456, 4567, 78]

The above method is an ordinary solution that iterates through the array of two for loops and their children:

Create a results variable to store the maximum values that are traversed in each child array

Create outer loop for traversal outer array

Create a second variable largestnumber to hold the maximum value. This variable value must be placed outside of the internal for loop, so that he will not be reassigned

Create a second for loop to traverse each element in the child array

An If statement is used to determine whether the element of the current child array is greater than the current stored maximum value largestnumber. If it is (true), store this maximum value to Largestnumber.

At the end of the internal loop, store the maximum value in each child array in the original declared variable results

Finally returns the results array

After you remove each of the maximum values from all the child arrays, you get a new array, results, which requires a single pass:

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

You can get the maximum value.

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

Intermediate Solutions

function Largestoffour (arr) {
//through the map () method, and through the callback function, combines the largest values in the child array to get a new array return
Arr.map (function (group) {
//Through the reduce method, return the maximum value in each child array to the group array returns
Group.reduce (function (prev, current) {
//if current is greater than Prev, Return to current, otherwise return prev returns
(Current > prev)? current:prev;
});} Largestoffour ([[[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]]); [34, 456, 4567, 78]

Use the Array.prototype.map () method to traverse an array in an outer-layer array. Traversing an array using the map () method invokes a callback function, in which the reduce () method is used to merge each of the child array group and return the value to a new array. In the case of the reduce () method, a callback function is also invoked, and the callback function only does one thing, that is, the elements in the child array are compared, and if current is greater than Prev, the current is returned, otherwise the Prev is returned, resulting in the maximum value in each of the child arrays.

As before, the maximum value is eventually obtained by Math.max.apply ().

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 scenario uses the Function.bind method to create a special callback function similar to the Math.max method, but it has a Function.prototype.apply function that takes the array as its arguments.

Iterate over each element in the main array, that is, each of the arrays inside the array

Using the map () method requires a callback function to find the maximum value within each array. You need to create a function that allows Math.max to accept the input of the array work. In other words, it is very simple and it works very well, such as Math.max ([9,43,20,6]); will return the maximum value of 43

Function.prototype.apply method work can take an array as a parameter, but the function is somewhat complicated by invoking the context. For example, Math.max.apply (null,[9,43,20,6]) will invoke a Max.max method, but such a method is not easy to find.

This passes a null argument to the Function.prototype.apply method, telling the Math.max that no context is required.

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 a Function.prototype.apply bind a Function.prototype.bind. For example: Function.apply.bind

You can now specify its context through the Function.prototype.apply.bind callback function, such as the Math.max method in this example

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

So we pass NULL as the second argument to Function.prototype.apply.bind and bind a context, which is the Math.max method

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

We use Function.prototype.apply.bind (math.max,null) to let a new function accept arr.map values, such as a child array in an array

Take the maximum value in a multidimensional array

Using different methods to extract the maximum value from a two-dimensional array, and then rearrange the maximum values into a new array, you need to use the Array.prototype.max function when extending the maximum value in the function, which is passed through the Math.max.apply ( {},this) gets the maximum value. However, if it is not a two-dimensional array, the above method will not be able to retrieve the largest value in the array.

The maximum value in a multidimensional array can be grouped together by the join () and Split () methods:

function Largestoffour (arr) {
var newarray = Arr.join (","). Split (",");
Return Math.max.apply ({},newarray);
}
Largestoffour ([12,23]); =>23
Largestoffour ([12,23,[1234,324],[345,566]]);//=>1234
largestoffour ([12,23,[1234,324,[ 23121,90890]],[345,566,[345,78,90]]); =>90890
Largestoffour ([12,23,[1234,324,[23121,90890]],[345,566,[345,78,90,[90909090,988]]]);//=> 90909090

You can also use a similar method to remove the smallest value in a multidimensional array:

function Smalleroffour (arr) {
var newarray = Arr.join (","). Split (",");
Return Math.min.apply ({},newarray);
}
Smalleroffour ([12,23]); =>12
Smalleroffour ([112,23,[1234,324],[345,566]]);//=>23
smalleroffour ([212,123,[1234,324,[ 23121,90890]],[345,566,[345,78,90]]); =>78
Smalleroffour ([102,230,[1234,324,[23121,90890]],[345,566,[345,78,90,[90909090,988]]]);//=> 78

Summarize

Use Math.max.apply ({},arr) to get the largest number in an array, as described in "JavaScript Learning notes: Taking the maximum and minimum values in an array." This article from a different point of view on how to take out the largest number of two-dimensional arrays, but many times, the array also has a multidimensional array, the article finally describes how to achieve the maximum size of a multidimensional array. If you have more options, please share them with us in the 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.