Home Web Front-end JS Tutorial Summary of methods to get the maximum value in a two-dimensional array in JS_javascript skills

Summary of methods to get the maximum value in a two-dimensional array in JS_javascript skills

May 16, 2016 pm 03:05 PM

In JavaScript, you can use the built-in Math.max() to get the maximum value, but it is still difficult to get the maximum value from a multiple array.

Problem Description

Suppose you have an array, and this array contains subarrays of numbers, and what we want to do is to return the largest number from each subarray in the array.

Basic Solution

function largestOfFour(arr) {
var results = []; // 创建一个results变量来存储
// 创建一个外层循环,遍历外层数组
for (var n = 0; n < arr.length; n++) {
var largestNumber = 0; // 创建第二个变量,存储最大的数
// 创建另一个循环,遍历子数组
for (var sb = 0; sb < arr[n].length; sb++) {
//检查子数组的元素是否大于当前存储的最大值
if (arr[n][sb] > largestNumber) {
// 如果为真,将这个值赋予给变量largestNumber
largestNumber = arr[n][sb];
}
}
// 内部循环后,将每个子数组中的值保存到数组results中
results[n] = largestNumber;
}
// 返回数组
return results;
}
largestOfFour([[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]]); //[34, 456, 4567, 78]
Copy after login

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

Create a results variable to store the maximum value traversed in each sub-array

Create an outer loop for to traverse the outer array

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

Create a second for loop to iterate over each element in the subarray

Use an if statement to determine whether the elements of the current subarray are greater than the currently stored maximum value largestNumber. If true ( true ), store this maximum value in largestNumber .

After the inner loop ends, store the maximum value in each sub-array into the originally declared variable results

Finally return the results array

After taking out each maximum value in all sub-arrays, a new array results is obtained. At this time, you only need to pass:

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

You can get the maximum value among them.

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

Intermediate solution

function largestOfFour (arr) {
// 通过map()方法,并通过回调函数,将子数组中最大值组合在一起,得到一新数组
return arr.map(function (group) {
// 通过reduce方法,把每个子数组中最大值返回到group数组中
return group.reduce(function (prev, current) {
// 如果current 大于prev,返回current,否则返回prev
return (current > prev) &#63; current : prev;
});
});
}
largestOfFour([[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]]); // [34, 456, 4567, 78]
Copy after login

Use the Array.prototype.map() method in the outer array to traverse the array. Using the map() method to traverse the array will call a callback function. In this callback function, use the reduce() method to merge each sub-array group and return the value to a new array. When using the reduce() method, a callback function will also be called. This callback function only does one thing, which is to compare the elements in the subarray. If current is greater than prev, current will be returned, otherwise prev will be returned. Finally, the maximum value in each subarray is obtained.

Same as before, use Math.max.apply() to finally get 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]
Copy after login

这个方案,使用 Function.bind 方法创建一个特殊的回调函数,就类似于 Math.max 方法一样,但其有一个 Function.prototype.apply 功能,将数组作为它的参数。

先对主数组中的每个元素做遍历,也就是数组内部的每个子数组

使用 map() 方法需要一个回调函数,用来找出内部每个数组中的最大值。需要创建一个函数,让 Math.max 能接受输入的数组工作。换句话说,这是非常简单而且这样工作也非常的好,如 Math.max([9,43,20,6]); 将会返回最大值 43

Function.prototype.apply 方法工作可以接受数组做为参数,但函数通过调用上下文,这事情就有点复杂。例如 Math.max.apply(null,[9,43,20,6]) 将调用一个 Max.max 方法,但这样的方法找起来不容易。

这里给 Function.prototype.apply 方法传递了一个 null 参数,告诉 Math.max 不需要任何上下文。

因为 arr.map() 需要一个回调函数,而不只是一个表达式,我们在 Function.bind 方法中提供了一个函数

因为 Function.prototype.apply 是一个静态方法,类似一个函数对象,我们可以称之为 Function.prototype.apply 上绑定了一个 Function.prototype.bind 。例如: Function.apply.bind

现在可以通过 Function.prototype.apply.bind 回调函数指定其上下文,比如在这个示例中的 Math.max 方法

由于是嵌入到 Function.prototype.apply 方法,需要一个上下文作为第一个参数,而且这个上下文还是一个虚假的。

所以我们将 null 作为第二个参数传递给 Function.prototype.apply.bind ,并且绑定一个上下文,这个上下文就是 Math.max 方法

由于 Math.max 是独立于任何上下文的,所以它会忽略 Function.prototype.apply 方法调用的虚假上下文

我们使用 Function.prototype.apply.bind(Math.max,null) 让一个新函数接受 arr.map 值,比如数组中的子数组

多维数组中取最大值

上文使用不同的方法实现了从二维数组中取出子数组中最大值,并且将这些最大值重新组成一个新数组,如果延伸一下,取出里面的最大值时,还需要使用 Array.prototype.max 函数,函数中通过 Math.max.apply({},this) 取得最大值。不过如果不是二维数组,那上述方法将无法取出数组中最大的值。

而在多维数组中取最大值,可以通过 join() 和 split() 方法组合在一起:

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
Copy after login

同样可以使用类似的方法取出多维数组中的最小值:

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
Copy after login

总结

在《 JavaScript学习笔记:取数组中最大值和最小值 》一文中介绍了使用 Math.max.apply({},arr) 来取数组中最大的数字。这篇文章中从不同的角度的介绍了如何在二维数组中取出最大的数,但很多时候,数组还有多维数组,文章最后介绍了如何实现多维数组中取出最大值。如果您有更多的方案,欢迎在评论中与我们一起分享。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles